알고리즘 고득점 Kit > 스택/ > 주식가격
주식가격 Lv.2
초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요.
[제한사항]
- prices의 각 가격은 1 이상 10,000 이하인 자연수입니다.
- prices의 길이는 2 이상 100,000 이하입니다.
첫 번째 풀이 : 6.7점
from collections import deque
def solution(prices):
answer = [0 for _ in range(len(prices))]
q = deque(prices)
for i in range(len(prices)):
for j in range(i+1, len(prices)):
if prices[i]<=prices[j]:
answer[i]+=1
return answer
- 테케는 맞았으나 히든케이스를 맞추지 못함
- for문을 두 번 돌려서 시간초과도 남
두 번째 풀이: 100점
from collections import deque
def solution(prices):
answer = []
q = deque(prices)
while q:
cnt = 0
c = q.popleft()
for i in q:
cnt+=1
if c > i:
break
answer.append(cnt)
return answer
- while q: q.pop()을 통해 for문을 대신 할 수 있음
'코딩테스트 | python > 프로그래머스' 카테고리의 다른 글
| [프로그래머스 | python] H-Index (0) | 2024.04.04 |
|---|---|
| [프로그래머스 | python] 가장 큰 수 (0) | 2024.04.04 |
| [프로그래머스 | python] 가장 먼 노드 (0) | 2024.04.02 |
| [프로그래머스 | python] 올바른 괄호 (0) | 2024.03.28 |
| [프로그래머스 | python] 무인도 여행 (0) | 2024.03.13 |