728x90

https://programmers.co.kr/learn/courses/30/lessons/42584

 

코딩테스트 연습 - 주식가격

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

programmers.co.kr

출처 : 프로그래머스


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

풀이 1 

이중포문을 사용해서 효율성은 떨어진다.

문제 카테고리에 맞게 스택/큐를 사용해봐야겠다.

 

from collections import deque

def solution(prices):
    answer = []
    prices = deque(prices)
    while prices:
        p = prices.popleft()
        cnt = 0
        for pq in prices:
            if p > pq:
                cnt += 1
                break
            cnt += 1
        answer.append(cnt)
    return answer

풀이 2

큐를 이용해 풀이했다.

prices 배열을 큐로 변환해서 풀이한거 말고는 이중반복문이랑 비슷하다.

+ Recent posts