문제 설명
초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요.
제한사항
- prices의 각 가격은 1 이상 10,000 이하인 자연수입니다.
- prices의 길이는 2 이상 100,000 이하입니다.
입출력 예
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초간 가격이 떨어지지 않았습니다.
https://programmers.co.kr/learn/courses/30/lessons/42584
코딩테스트 연습 - 주식가격
초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요. 제한사항 prices의 각 가격은 1 이상 10,00
programmers.co.kr
내 소스
import java.util.Stack;
class Solution {
public int[] solution(int[] prices) {
int[] answer = new int[prices.length];
int idx;
Stack<Integer> prc_stk = new Stack<>();
Stack<Integer> idx_stk = new Stack<>();
for(int i=0; i<prices.length; i++){
if(prc_stk.empty() || prc_stk.peek()<=prices[i]){
prc_stk.push(prices[i]);
idx_stk.push(i);
}else {
while(!prc_stk.empty() && prc_stk.peek()>prices[i]){
prc_stk.pop();
idx = idx_stk.pop();
answer[idx] = i - idx;
}
prc_stk.push(prices[i]);
idx_stk.push(i);
}
}
while(!prc_stk.empty()){
int temp = prc_stk.pop();
idx = idx_stk.pop();
answer[idx] = prices.length - idx - 1;
}
return answer;
}
}
'Algorithm' 카테고리의 다른 글
[백준/문자열] 2941 - 크로아티아 알파벳 (0) | 2021.08.01 |
---|---|
[프로그래머스/해시] 베스트앨범 (0) | 2021.08.01 |
[프로그래머스/정렬] H-Index (0) | 2021.08.01 |
[프로그래머스/이분탐색] - 입국심사 (0) | 2021.08.01 |
[프로그래머스/완전탐색] 카펫 (0) | 2021.08.01 |