만약 stack이 비어있다면 stack에 현재위치를 저장하고 비어있지 않고,stack.peek()위치의 prices가 이번 price보다 크다면 stack에서 pop 하고 stack.pop() 한 위치에 현위치(i)-stack.peek() 를 하여 가격이 저장된 길이를 삽입한다.
for문이 끝나고 stack에 남아있는 위치가 있다면 이는 마지막 이 될때까지 가격이 떨어진 적이 없으니 prices.length에서 stack.peek()를 빼고 -1을 하여 가격이 떨어지지 않았던 길이를 구해낸다.
import java.util.*;
class Solution {
public int[] solution(int[] prices) {
int[] answer = new int[prices.length];
Stack<Integer> stack = new Stack<>();
for(int i = 0 ; i < prices.length ; i++){
while(!stack.isEmpty() && prices[stack.peek()]>prices[i]){
answer[stack.peek()] = i - stack.peek();
stack.pop();
}
stack.push(i);
}
while(!stack.isEmpty()){
answer[stack.peek()] = prices.length - stack.peek() - 1;
stack.pop();
}
return answer;
}
}