파이썬 알고리즘 : 주식가격

스택

2024년 4월 23일 알고리즘 문제풀이

문제

난이도

Lv. 2

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def solution(prices):
    answer = [0 for _ in range(len(prices))]
    stk = []
    for i in range(len(prices)):
        price = prices[i]
        if not stk:
            stk.append([price,i])
            continue
        while stk:
            now_price, now_time = stk[-1]
            if price < now_price:
                answer[now_time] = (i-now_time)
                stk.pop()
            else:
                break
        stk.append([price,i])
    if stk:
        while stk:
            p,t = stk.pop()
            answer[t] = len(prices)-1-t
    return answer