코딩 테스트/프로그래머스 level2

주식가격 (stack 기본 예제)

fullfish 2025. 9. 30. 09:43

def solution(prices):
    n = len(prices)
    result = [0] * n
    stack = []  # 아직 기간이 확정되지 않은 인덱스들

    for i, price in enumerate(prices):
        # 가격이 떨어졌을 때 이전 가격들의 기간을 확정
        while stack and prices[stack[-1]] > price:
            j = stack.pop()
            result[j] = i - j
        stack.append(i)

    # 끝까지 안 떨어진 경우 처리
    while stack:
        j = stack.pop()
        result[j] = n - 1 - j

    return result