알고리즘

프로그래머스 주식가격 (JAVA)

박카스마시며코딩 2022. 6. 15. 21:51

https://programmers.co.kr/learn/courses/30/lessons/42584

 

코딩테스트 연습 - 주식가격

초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요. 제한사항 prices의 각 가격은 1 이상 10,00

programmers.co.kr

 

저는 스택을 통해 문제를 해결하였습니다.

스택은 현재 가격보다 작은 인덱스를 가지고 있게 하여 해당 값이 작다면 현재 인덱스를 비교하여 가격이 안 떨어지고 얼마나 있었는지를 계산하였습니다.

 

import java.util.*;
class Solution {
    public int[] solution(int[] prices) {
        int size = prices.length;
        int[] answer = new int[size];
        int upLength = 0;
        ArrayDeque<Integer> stack = new ArrayDeque<>();
        for(int i = 0 ; i < size ; i++){
            while(!stack.isEmpty() && prices[i] < prices[stack.peek()]){
                int index = stack.poll();
                answer[index] = i -index;
            }
            stack.push(i);
        }
        while(!stack.isEmpty()){
            int index = stack.poll();
            answer[index] = size -1 -index;
        }
            
        return answer;
    }
}