본문 바로가기

Coding Test/Programmers

[프로그래머스/파이썬] 주식가격

728x90

나의 풀이

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

    answer.append(0)
    return answer

 

 

 

deque를 이용한 풀이

from collections import deque
def solution(prices):
    answer = []
    prices = deque(prices)
    while prices:
        c = prices.popleft()

        count = 0
        for i in prices:
            if c > i:
                count += 1
                break
            count += 1

        answer.append(count)

    return answer

 

 

 

스택과 인덱스를 활용한 풀이

def solution(p):
    ans = [0] * len(p)
    stack = [0]
    for i in range(1, len(p)):
        if p[i] < p[stack[-1]]:
            for j in stack[::-1]:
                if p[i] < p[j]:
                    ans[j] = i-j
                    stack.remove(j)
                else:
                    break
        stack.append(i)
    for i in range(0, len(stack)-1):
        ans[stack[i]] = len(p) - stack[i] - 1
    return ans

 

 

 

스택을 이용한 풀이 2

def solution(prices):
    stack = []
    answer = [0] * len(prices)
    for i in range(len(prices)):
        if stack != []:
            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
반응형