초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요.
prices
의 마지막 아이템이라면 무조건 0을 answer 배열에 넣어준다.cur
)를 저장해놓고, iter
라는 새로운 반복문을 돌 인덱스를 만들어서 cur
보다 작은 값을 만날 때까지 iter
와 duration
을 증가시키면서 돈다.prices
끝까지 갔을 때는 duration
을 반환해주고, 아니라면 duration + 1
을 반환해준다. (while문의 조건을 내가 그렇게 짜서..)function solution(prices) {
let answer = Array(prices.length).fill(0);
for(let i=0; i<prices.length; i++) {
let cur = prices[i];
//마지막 가격인 경우
if(i === prices.length - 1) {
answer[i] = 0;
break;
}
//다음가격이 현재가격 이상인 경우
if(cur <= prices[i+1]) {
let iter = i+1;
let duration = 0;
while(cur <= prices[iter] && iter < prices.length) {
duration++;
iter++;
}
answer[i] = iter === prices.length ? duration : duration + 1;
}
//다음거가 현재가격 미만인 경우
else if(cur > prices[i+1]){
answer[i] = 1;
}
}
return answer;
}
from collections import deque
def solution(prices):
answer = []
deq = deque(prices)
while len(deq):
cur = deq.popleft()
# 남은 deq에서 현재보다 작은 값이 나오면 시간을 세다가 answer에 넣는다.
time = 0
for p in deq:
time += 1
if(p < cur):
break
answer.append(time)
time = 0
return answer
def solution(prices):
stack = []
answer = [-1 for _ in range(len(prices))]
for i, price in enumerate(prices):
while stack and price < stack[-1][0]:
pop_price, pop_i = stack.pop()
answer[pop_i] = i - pop_i
stack.append([price, i])
#마지막에 남은 stack들 해소해주기
for s in stack:
pop_price, pop_i = s
answer[pop_i] = len(prices) - pop_i - 1
return answer