코딩문제풀이/프로그래머스

[Python] 주식 가격

코딩하는 포메라니안 2021. 8. 26. 00:01

1. 문제

 

 

 

2. 풀이 과정

 

방법 1) 직관적으로 생각나는 방법, 자신보다 뒤에 있는 값을 하나씩 확인해서 계산한다. 시간복잡도 O(%{n}^2%)

def solution(prices):
    answer = []
    
    for i in range(len(prices)):
        for j in range(i+1, len(prices)):
            if prices[i] > prices[j]:
                answer.append(j-i)
                break
        if len(answer)-1 < i:
            answer.append(len(prices)-1-i)
    
    return answer

 

방법 2) stack을 이용해서 더 빨리 계산한다.

코드 실행 과정 예시
입력 : [1, 2, 3, 2, 1]
stack
[(1, 0)]
[(1, 0), (2, 1)]
[(1, 0), (2, 1), (3, 2)]
[(1, 0), (2, 1), (2, 3)]
[(1, 0), (1, 4)]
def solution(prices):
    answer = [0]*len(prices)
    stack = []
    
    for i in range(len(prices)):
        while stack and stack[-1][0] > prices[i]:
            p, idx = stack.pop()
            answer[idx] = i - idx
        stack.append((prices[i], i))
        
    #stack에는 prices에서 최소값인 element들만 남음
    while stack:
        p, idx = stack.pop()
        answer[idx] = len(prices)-1-idx
    
    return answer

'코딩문제풀이 > 프로그래머스' 카테고리의 다른 글

[Python] 가장 큰 수  (0) 2021.08.26
[Python] 더 맵게  (1) 2021.08.26
[Python] 다리를 지나는 트럭  (0) 2021.08.25
[Python] 프린터  (0) 2021.08.25
[Python] 기능 개발  (0) 2021.08.24