ํ’€์ด

prices์˜ ๊ธธ์ด๊ฐ€ 100,000์ด๋ผ n^2์œผ๋กœ ์งœ๋ฉด ํ„ฐ์งˆ ๊ฒƒ ๊ฐ™์•„ stack์œผ๋กœ ๊ตฌํ˜„ํ–ˆ๋‹ค. ๊ทธ๋Ÿฐ๋ฐ ์ด๋•Œ, ํŠน์ • ์›์†Œ๊ฐ€ ์กฐ์‚ฌํ•ด์•ผ ํ•˜๋Š” ๋ถ€๋ถ„์€ i+1๋ถ€ํ„ฐ ๋๊นŒ์ง€์˜ ์š”์†Œ์ด๋‹ค. ๊ทธ ๊ณผ์ •์—์„œ ์ค‘๋ณต์ด ๋ฐœ์ƒํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋ฐ˜๋Œ€๋กœ ์ •๋ ฌํ•œ๋’ค ๊ฐ’์„ ๊ตฌํ•ด์ฃผ์—ˆ๋‹ค.

๊ทผ๋ฐ ๋ฌธ์ œ๋Š”, n^2์œผ๋กœ ํ’€์–ด๋„ ํ†ต๊ณผํ•œ๋‹ค๋Š” ์ ์ด๋‹ค..ํ•˜..

Code

def solution(prices):
    # prices = [4, 3, 1, 4, 5, 2, 7, 2, 3, 4]
    # prices = [1, 2, 3, 2, 3, 1]
    reverse_prices = prices[::-1]
    stack, ans = [], []
    for i in range(len(reverse_prices)):
        now = reverse_prices[i]
        if not stack: 
            ans.append(0)
            stack.append(now)
            continue
        last = stack[-1]
        
        if now <= last:
            # ์•ž์œผ๋กœ ๊ฐ€๋ฉด์„œ ์ฐพ์•„
            idx, count = len(stack)-1, 0
            while idx >= 0:
                if stack[idx] < now:
                    break
                count += 1
                idx -= 1
            if idx < 0:
                ans.append(count)
            else:
                ans.append(count+1)
            stack.append(now)
        else:
            ans.append(1)
            stack.append(now)
    return ans[::-1]

ํ’€์ด 2

์ข€ ๋‹จ์ˆœํ•˜๊ฒŒ ๋‹ค์‹œ ์ƒ๊ฐํ•ด๋ดค๋‹ค. ๊ฒฐ๊ตญ ๋ฌธ์ œ ์ƒ๊ธฐ๋Š” ๊ฒƒ์€ ๊ฐ€๊ฒฉ์ด ๋œ์–ด์กŒ์„ ๋•Œ์ด๋‹ค. ๊ทธ ๋•Œ ์–ด๋–ป๊ฒŒ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ค„๊นŒ? ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์ง€๋Š” ์ด๋ฒคํŠธ๊ฐ€ ๋ฐœ์ƒํ–ˆ์„ ๋•Œ, ์ง€๊ธˆ ๊ฐ€๊ฒฉ์ด์ „์˜ ๊ฐ€๊ฒฉ๋“ค์„ ๋ณด๋ฉด์„œ ๊ทธ๋ƒฅ ๊ทธ ๊ฑฐ๋ฆฌ๊ฐ€ ์–ผ๋งˆ์ธ์ง€ ์ฒดํฌํ•ด์ค€๋‹ค. ๊ทธ๋Ÿฌ๋ฉด ์ด์ „ ๊ฐ€๊ฒฉ๋“ค ์ค‘์— ํ˜„์žฌ ๊ฐ€๊ฒฉ์œผ๋กœ ์ธํ•ด์„œ ๊ฐ€๊ฒฉ์ด ๋–จ์–ด์กŒ๋‹ค๊ณ  ํŒ๋‹จ๋œ ๋…€์„๋“ค์€ ์ด๋ฏธ ๋‹ต์„ ๊ตฌํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— ๋‹ค์‹œ ๋ณผ ํ•„์š”๊ฐ€ ์—†๋‹ค.

์•„.. ๊ต‰์žฅํžˆ ์‰ฌ์šด ๊ฒƒ์ด์˜€๊ตฐ.. ์ด๊ฑฐ ๋ฐฑ์ค€์—์„œ ํ’€์–ด๋ณธ ๊ธฐ์–ต์ด ์žˆ๋‹ค. ์ผ๋‹จ index๋ฅผ stack์— ๋„ฃ๋Š” ์•„์ด๋””์–ด. ๊ทธ๋ฆฌ๊ณ  stack์•ˆ์˜ ์›์†Œ๋ฅผ ์ฆ๊ฐ€ํ•˜๋Š” ๋ฐฉํ–ฅ์œผ๋กœ ๋งŒ๋“ค์–ด์„œ ์ž‘์—…์„ ์ง„ํ–‰ํ•˜๋Š” ์•„์ด๋””์–ด๊ฐ€ ์žˆ๋˜ ๊ฒƒ์ด ๊ธฐ์–ต๋‚œ๋‹ค.

code 2

def solution(prices):
    ans, stack = [0] * len(prices), []
    
    for now, price in enumerate(prices):
        if stack:
            while stack and price < prices[stack[-1]]: # ์Šคํƒ์•ˆ์— ์›์†Œ๊ฐ€ ์žˆ๊ณ , ํ˜„์žฌ๊ฐ€๊ฒฉ์ด ์ด์ „ ๊ฐ€๊ฒฉ๋ณด๋‹ค ๋–จ์–ด์กŒ๋‹ค๋ฉด
                past = stack.pop()
                ans[past] = now-past
        stack.append(now)
    for i in stack: # ์ด์ œ ์Šคํƒ์€ ๋น„๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ๋˜์–ด ์žˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๊ทธ ์•ˆ์˜ ์›์†Œ๋Š” ์‹œ๊ฐ„์ž„. ์ง€๊ธˆ๊นŒ์ง€ ์‚ด์•„์žˆ๋Š” ์›์†Œ๋Š” ๋๊นŒ์ง€ ๋Œ์•˜๋Š”๋ฐ๋„ ๋‚จ์•„์žˆ๋Š” ๊ฒƒ๋“ค์ž„
        ans[i] = len(prices)-(i+1) # ์ด ์‹œ๊ฐ„์—์„œ ํ•ด๋‹น ๊ฐ€๊ฒฉ์˜ ์‹œ๊ฐ„์„ ๋นผ์ค€๋‹ค.
    return ans

Reference