주식 계산
초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요.
prices | return |
---|---|
[1, 2, 3, 2, 3] | [4, 3, 1, 1, 0] |
1초 시점의 ₩1은 끝까지 가격이 떨어지지 않았습니다.
2초 시점의 ₩2은 끝까지 가격이 떨어지지 않았습니다.
3초 시점의 ₩3은 1초뒤에 가격이 떨어집니다. 따라서 1초간 가격이 떨어지지 않은 것으로 봅니다.
4초 시점의 ₩2은 1초간 가격이 떨어지지 않았습니다.
5초 시점의 ₩3은 0초간 가격이 떨어지지 않았습니다.
효율성 테스트 1,3 번에서 계속 오류 발생
from collections import deque
def solution(prices):
answer = [] #deque([0 for _ in range(prices)])
queue = deque(prices)
while queue:
current = queue.popleft()
length = 0
for i in range(len(queue)):
if queue[i] >= current:
length += 1
else: # 현재보다 작다면
length += 1
break
answer.append(length)
return answer
from collections import deque
def solution(prices):
answer = []
queue = deque(prices)
while queue:
current = queue.popleft()
length = 0
for i in queue: #range 대신 queue 사용
length += 1 # 중복된 코드 공통으로 빼버림
if i < current: # 조건을 반대로 설정하여 코드 단축
break
#else: # 현재보다 작다면
#length += 1
#break
answer.append(length)
return answer
정말 잘 읽었습니다, 고맙습니다!