주식가격이 초 단위로 들어오는데 각 가격당 가격이 떨어지지 않은 기간이 얼마나 되는지 구하는 문제이다.
스택을 활용하였다.
prices배열을 돌면서 스택에 가격 값과 인덱스를 넣어주는데,
price 값이 스택의 peek보다 가격이 크면 그대로 스택에 넣어주고
peek보다 작으면 가격이 내려갔다는 뜻이므로 answer값에 인덱스 차이값을 넣어준 뒤 pop한다
peek보다 크거나 같은 값 나올 때 까지 위의 과정 반복
import java.util.*;
class Solution {
public int[] solution(int[] prices) {
Stack<Node> myStack = new Stack<>();
int leng = prices.length;
int[] answer = new int[leng];
for(int i = 0; i < leng; i++){
while(!myStack.isEmpty() && myStack.peek().stockPrice > prices[i]){
answer[myStack.peek().sec] = i - myStack.peek().sec;
myStack.pop();
}
myStack.push(new Node(prices[i], i));
}
while(!myStack.isEmpty()){
answer[myStack.peek().sec] = leng - myStack.peek().sec - 1;
myStack.pop();
}
return answer;
}
static class Node{
int stockPrice;
int sec;
public Node(int stockPrice, int sec){
this.stockPrice = stockPrice;
this.sec = sec;
}
}
}
이런 류의 스택문제를 사실 많이 어려워했었따. 그래도 풀리는걸 보니 조금은 성장했나보다..ㅎㅎ