문제
https://programmers.co.kr/learn/courses/30/lessons/42584
코드
def solution(prices):
answer = [] *len(prices)
for i in range(len(prices)):
index=-1
for j in range(i+1, len(prices)):
if prices[i]>prices[j]:
index=j
break
if index==-1:
answer.append(len(prices)-i-1)
else:
answer.append(index-i)
return answer
생각 정리
스택을 이용하면 시간 복잡도를 더 줄일 수 있다.
def solution(prices):
answer = [0]*len(prices)
stack = []
for i, price in enumerate(prices):
#stack이 비었이면 false
while stack and price < prices[stack[-1]]:
j = stack.pop()
answer[j] = i - j
stack.append(i)
# for문 다 돌고 Stack에 남아있는 값들 pop
while stack:
j = stack.pop()
answer[j] = len(prices) - 1 - j
return answer
출처: https://deftkang.tistory.com/175 [deftkang의 IT 블로그]
스택으로 푸는 방법은 처음 price를 stack에 쌓고 다음 price가 더 크면 스택에 쌓고 작으면 pop을 한다.
'문제풀이 > 기타' 카테고리의 다른 글
[파이썬] [힙] Pro 이중우선순위큐 (0) | 2022.02.13 |
---|---|
[파이썬] [힙] Pro 더 맵게 (0) | 2022.02.12 |
* [파이썬] [스택/큐] Pro 다리를 지나는 트럭 (0) | 2022.02.11 |
[파이썬] [스택/큐] Pro 프린터 (0) | 2022.02.11 |
[파이썬] [스택/큐] Pro 기능개발 (0) | 2022.02.11 |