2023.04.16 Complete !
초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요.
prices | return |
---|---|
[1, 2, 3, 2, 3] | [4, 3, 1, 1, 0] |
import java.util.*;
class Solution {
public int[] solution(int[] prices) {
int[] answer = new int[prices.length];
Stack<Integer> stk = new Stack<>(); // 얼마나 버티고 있는지 체크하기 위해서
for(int i=0; i<prices.length; i++){
while(!stk.isEmpty() && prices[i] < prices[stk.peek()]){
answer[stk.peek()] = i-stk.peek();
stk.pop();
}
stk.push(i);
}
while(!stk.isEmpty()){
answer[stk.peek()] = prices.length-stk.peek()-1;
stk.pop();
}
return answer;
}
}
→ 처음에는 간단하게 이중 for문으로 풀어봤으나, 이렇게 풀면 시간복잡도 선에서 좋지 않다길래 스택/큐 분야에 있으니 스택으로 어떻게 풀었나 찾아보았다.
처음에 스택으로 푼 것을 이해하는것이 어려웠다.
결론은 prices[stk.peek()] 하는 과정이 stk에 인덱스가 들어가있으니 지금 인덱스와 peek 한 인덱스 배열의 값을 확인하고 인덱스 차이를 통해 유지한 시간을 파악하는 것이였다.
많은 똑똑한 분들의 코드를 보며 배워나가는 것 같다 ❗
참고 2중 for문 풀이
class Solution { public int[] solution(int[] prices) { int len = prices.length; int[] answer = new int[len]; int i, j; for (i = 0; i < len; i++) { for (j = i + 1; j < len; j++) { answer[i]++; if (prices[i] > prices[j]) break; } } return answer; } }
💡 참고한 블로그
https://girawhale.tistory.com/7
https://velog.io/@geesuee/프로그래머스-주식가격자바
( 이 분도 위에 블로그를 보셨다고 하셨다 )