파이썬 알고리즘 문제 풀이

[프로그래머스] Lv2. 주식 가격

gogi masidda 2024. 9. 6. 16:28
주식가격
문제 설명

초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요.

제한사항
  • prices의 각 가격은 1 이상 10,000 이하인 자연수입니다.
  • prices의 길이는 2 이상 100,000 이하입니다.
입출력 예pricesreturn
[1, 2, 3, 2, 3] [4, 3, 1, 1, 0]

내 풀이

def solution(prices):
    answer = []
    for i in range(len(prices)):
        for j in range(i, len(prices)):
            if prices[i] > prices[j]:
                answer.append(j - i)
                break
            else:
                if j == len(prices) - 1:
                    answer.append(len(prices) - 1 - i)
                else:
                    continue
    return answer
  • if: i초의 가격이 j초의 가격보다 비싸면 가격이 떨어진 것이므로 j-i만큼을 answer에 추가한다.
  • else
    • if: j를 끝까지 돌았으면 가격이 끝까지 떨어지지 않은 것이므로 len(prices) - 1 - i를  answer에 추가한다. (사실 j - i 와 같음)
    • else: 끝까지 돌지 않았으면 계속 반복을 실행한다. 

 

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

이렇게 해도 같다.

 

다른 사람 풀이

def solution(prices):
    stack = []
    answer = [0] * len(prices)
    for i in range(len(prices)):
        while stack != [] and stack[-1][1] > prices[i]:
            past, _ = stack.pop()
            answer[past] = i - past
        stack.append([i, prices[i]])
    for i, s in stack:
        answer[i] = len(prices) - 1 - i
    return answer

스택을 이용한 풀이로 내 풀이보다 이 풀이가 문제 취지에 더 맞다고 생각이 든다.

  • for: prices 배열 순회
    • while: stack이 비어있지 않고, stack의 최상단에 있는 가격이 현재가인 prices[i]보다 크면 가격이 하락한 것. 그 동안에
      • 스택의 최상단 원소를 가져와서 떨어진 시점을 past로 받는다.
      • i - past를 answer[past[]값에 넣는다.
    • 스택에 i와 prices[i]를 추가한다.
  • for: stack을 순회한다.
    • stack에 아직 남아 있는 것은 끝까지 떨어지지 않은 것이라 len(prices) - 1 - i를 answer[i]에 넣는다. 
728x90