CS/Algorism

99클럽 코테 스터디 4일차 TIL: [프로그래머스] 주식가격

olsohee 2024. 5. 23. 12:38

스택을 이용해서 푸는 문제이다. 쉬웠는데 딱 한가지 실수는 while 문에서 !stack.isEmpty() 를 넣어주지 않아서 런타임 에러가 발생했다. while문을 돌면서 스택에 값이 모두 빠져 비어있는 경우에도 while문을 돌 수 있기 때문에 !stack.isEmpty() 를 잊지말고 꼭 넣어주자!

import java.util.*;

class Solution {
    public int[] solution(int[] prices) {
        
        Stack<Integer> stack = new Stack<>();
        int[] answer = new int[prices.length];
        
        for (int i = 0; i < prices.length; i++) {
            if (stack.isEmpty()) {
                stack.push(i);    
                continue;
            }
            
            while (!stack.isEmpty() && prices[stack.peek()] > prices[i]) {
                int idx = stack.pop();
                answer[idx] = i - idx;
            }
            
            stack.push(i);
        }
        
        while (!stack.isEmpty()) {
            int idx = stack.pop();
            answer[idx] = prices.length - 1 - idx;
        }
        
        return answer;
    }
}