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


코드

import java.util.Arrays;
import java.util.Stack;

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

        for (int i = 0; i < answers.length; i++) {
            while (!stack.isEmpty() && prices[i] < prices[stack.peek()]) {
                answers[stack.peek()] = i - stack.peek();
                stack.pop();
            }
            stack.push(i);
        }

        while (!stack.isEmpty()) {
            answers[stack.peek()] = prices.length - stack.peek() - 1;
            stack.pop();
        }
        return answers;
    }

    public static void main(String[] args) {
        int[] prices = {1, 2, 3, 2, 3};

        System.out.println(Arrays.toString(solution(prices)));
    }
}

풀이 및 느낀점

	while (!stack.isEmpty() && prices[i] < prices[stack.peek()]) {
		answers[stack.peek()] = i - stack.peek();
		stack.pop();
	}
	stack.push(i);

while문의 목적은 주식이 감소하는 구간을 찾기 위함이다.

현 위치의 값(prices[i])이 이전 위치의 값보다 작다면, answers[이전 위치 인덱스]에 <현위치 인덱스(i) - 이전위치 인덱스>를 저장해주면 된다.
그 다음, 스택에 저장된 최근 값(이전 위치 인덱스)을 빼주면 된다. while문을 벗어나면(감소구간이 종료되면), 현위치의 인덱스(i)를 스택에 저장했다.



while (!stack.isEmpty()) {

스택에 남아있는 값은 끝까지 감소구간이 없었다는 뜻이다. 그러므로 전체길이에서 해당 인덱스의 값을 빼주면 지속구간의 길이를 구할 수 있다.


참고자료

좋은 웹페이지 즐겨찾기