주식가격

 

 문제 설명

 

초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요.

 

 제한 사항

 

  • prices의 각 가격은 1 이상 10,000 이하인 자연수입니다.
  • prices의 길이는 2 이상 100,000 이하입니다.

 

 입출력 예

 

prices return
[1, 2, 3, 4, 5] [4, 3, 1, 1, 0]

 

 Python 코드

 

from collections import deque
def solution(prices):
queue = deque(prices) # prices로 queue를 초기화
answer = []
# 반복문 돌면서 앞에서부터 하나씩 popleft 한 뒤의 남은 queue를 순회하며 값이 작아지기 전까지
# 초를 증가시키는 것을 queue가 빌때까지 반복
while queue:
price = queue.popleft()
sec = 0
for q in queue:
sec += 1
if price > q:
break
answer.append(sec)
return answer

* 참고 링크 : https://velog.io/@soo5717/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EC%A3%BC%EC%8B%9D%EA%B0%80%EA%B2%A9-Python

def solution(prices):
answer = [0] * len(prices)
stack = []
for i, price in enumerate(prices):
while stack and price < prices[stack[-1]]:
j = stack.pop()
answer[j] = i - j
stack.append(i)
while stack:
j = stack.pop()
answer[j] = len(prices) - 1 - j
return answer

* 참고 링크 : 

def solution(prices):
# answer = 몇초 후 가격이 떨어지는지 저장하는 배열
answer = [len(prices)-i-1 for i in range(len(prices))]
# stack = prices의 인덱스를 차례로 담아두는 배열
stack = [0]
for i in range(1, len(prices)):
while stack:
index = stack[-1]
# 주식 가격이 떨어졌다면
if prices[index] > prices[i]:
answer[index] = i - index
stack.pop()
# 떨어지지 않았다면 다음 시점으로 넘어감 (주식 가격이 계속 증가하고 있다는 말)
else:
break
# 스택에 추가한다.
# 다음 시점으로 넘어갔을 때 다시 비교 대상이 될 예정이다.
stack.append(i)
return answer

* 참고 링크 : https://tngusmiso.tistory.com/34

 

 C++ 코드

 

#include <string>
#include <vector>
#include <stack>
using namespace std;
vector<int> solution(vector<int> prices) {
vector<int> answer(prices.size());
stack<int> s;
int size = prices.size(); // 계속 size를 계산하는 것보다 상수값으로 저장하면 전체 함수 처리 시간 감소
for (int i = 0; i < size; ++i){
while (!s.empty() && prices[s.top()] > prices[i]){ // 가격이 줄어들었다면
answer[s.top()] = i - s.top(); // 현재 시간 - 당시 시간
s.pop();
}
s.push(i);
}
while (!s.empty()){
answer[s.top()] = size - 1 - s.top(); // 종료 시간 - 당시 시간
s.pop();
}
return answer;
}

* 참고 링크 : https://ssocoit.tistory.com/15

 

 출처

 

https://programmers.co.kr/learn/courses/30/lessons/42584

+ Recent posts