본문 바로가기

Development

[프로그래머스] 주식가격

import java.util.Stack;

class Solution {
    public int[] solution(int[] prices) {
        int[] answer = new int[prices.length];
        int i;
        Stack<Integer> myPrices = new Stack<>();

        myPrices.push(0);
        for(i=1;i<prices.length;i++){
            if(prices[myPrices.peek()] <= prices[i]){
                myPrices.push(i);
            }
            else{
                while(true) {
                    int value = myPrices.pop();
                    answer[value] = i - value;
                    if(myPrices.empty() || prices[myPrices.peek()] <= prices[i]) break;
                }
                myPrices.push(i);
            }
        }
        i--;
        while(!myPrices.empty()){
            int value=myPrices.pop();
            answer[value]=i-value;
        }

        return answer;
    }
}