주식가격

이윤설·2024년 4월 16일
post-thumbnail

제출코드

없을 무

모범답안

import java.util.Stack;

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

        for (int i = 0; i < prices.length; i++) {
            while (!stack.isEmpty() && prices[i] < prices[stack.peek()]) {
                ans[stack.peek()] = i - stack.peek();
                stack.pop(); // 답을 구했기 때문에 stack에서 제거한다
            }
            stack.push(i);
        }
        
		// 값을 구하지 못한 index == 끝까지 가격이 떨어지지 않은 주식
        while (!stack.isEmpty()) { 
            ans[stack.peek()] = prices.length - stack.peek() - 1;
            stack.pop();
        }
        return ans;
    }
}

  • 만약 스택에 들어갈 숫자가 스택의 맨 위 요소(peek)보다 작으면 i - stack.peek한 값을 ans에 저장하고, 스택을 pop한다.
  • 반복문을 끝까지 돌았을 때, stack에는 제일 마지막에 추가된 4만이 존재하게 된다.
    stack에 끝까지 남아 있는 경우는 끝까지 주식 가격이 떨어지지 않는 경우이므로, stack이 비어있을 때까지 prices의 길이 - index - 1를 넣어준다.

참고

https://girawhale.tistory.com/7

profile
화려한 외면이 아닌 단단한 내면

0개의 댓글