
시도했던 틀린 답
def solution(prices): stack = [] n = len(prices) answer = [0]*n for i in range(n): while stack : j = stack.pop() if prices[i] >= prices[j]: answer[j] += 1 else: if prices[j] != 10001: answer[j] += 1 prices[j] = 10001 stack = [j for j in range(i+1)]우선 시간 상관없이 답이 나오도록 짜보았다
i가 0일 경우 stack에 0을 넣음
그 뒤로는 stack에 prices[i]보다 앞에 있는 원소들을 모두 넣은 뒤 하나씩 꺼내어서 prices[i]와 비교하여 만약 prices[i]가 크다면 answer에 1씩 더하고 stack 원소가 클 경우, answer에 1을 더하고 다음 prices 원소들과 비교할 수 없도록 stack 원소가 최대값인 10000보다 큰 수로 바꾼다.
prices 배열 값 변경, for문으로 stack 배열을 만드니깐 시간초과가 나왔다. stack 배열을 따로 만들지 않고 prices배열만을 사용하여 풀 수 있도록 해봄
from collections import deque
def solution(prices):
prices = deque(prices)
n = 0
answer = [0]*l
while prices:
price = prices.popleft()
if not prices : break
for i in prices:
if i >= price :
answer[n] += 1
else :
answer[n]+=1
break
print(answer)
n+=1
return answer
price의 가장 왼쪽 원소를 popleft()로 삭제하고 while문으로 뒤에 원소들과 하나씩 비교하여 만약 같거나 작다면 answer에 1을 더하고 크다면 break로 while문을 벗어나도록 함