[프로그래머스][Java] 주식가격 (Lv.2) - 스택/큐

박현아·2025년 2월 4일
0

programmers-java

목록 보기
33/35

👩‍💻 문제

🙋‍♀️ 답변

import java.util.Stack;

class Solution {
    public int[] solution(int[] prices) {
        
        int len = prices.length;
        int[] answer = new int[len];
        
        // 각 시간의 인덱스를 stack에 저장하기 위한 용도
        Stack<Integer> stack = new Stack<>();
        
        for(int i=0; i < len; i++) {
            // 빈 stack이 아니고, 현재 가격이 stack 맨 위 가격보다 작을 때
            while(!stack.isEmpty() && prices[i] < prices[stack.peek()]) {
                int idx = stack.pop();
                answer[idx] = i - idx;
            }
            stack.push(i);
        }
        
        // 가격이 떨어지지 않은 인덱스들 계산
        while(!stack.isEmpty()) {
            int idx = stack.pop();
            answer[idx] = len - 1 - idx;
        }

        return answer;
    }
}

⭐️

  • 각 시간의 인덱스를 저장하기 위해 stack을 만들어준다.
  • 0부터 prices.length까지 순회한다.
  • i=0일 때에는 stack이 빈 상태이기 때문에 stack.push(0);이 된다.
  • i=1일 때에는 prices[1]과 prices[0]을 비교한다. (prices[1] < prices[0]). while문을 만족하지 못 하기 때문에 stack.push(1);이 된다.
  • i=3일 때에는 prices[3]과 prices[2]를 비교한다. (prices[3] < prices[2]). while문을 만족하므로 stack에서 맨 위 값을 stack.pop() 해준다. answer[2] = 3 - 2 = 1 이 된다.

🤔

결국 stack으로 못 풀었지만 공부용으로 기록!
인덱스 개념이 0부터라 너무 헷갈린다,,,🥹 일일이 i=0부터 손으로 그려보고 나서야 이해했다,,,,

0개의 댓글