Coding Test/프로그래머스

[프로그래머스] 주식 가격 - 자바

lsh2613 2023. 8. 10. 16:26

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제 풀이

stack에는 prices의 인덱스를 추가

현재 참조하고 있는 price가 stack에 있는 인덱스가 가지는 값보다 작다면 해당 인덱스의 가격이 떨어지지 않은 기간을 계산

코드

import java.util.*;
class Solution {
    public int[] solution(int[] prices) {
        int[] answer = new int[prices.length];
        // 자신의 인덱스가 가지는 가격보다 더 낮은 가격을 찾기 위해 보관
        Stack<Integer> s = new Stack<>();
        
        for(int i=0; i<prices.length; i++){
            while(!s.isEmpty() && prices[s.peek()]>prices[i]){
                answer[s.peek()]=i-s.peek();
                s.pop();
                
                /*
                answer[s.peek()]=i-s.pop();
                */
            }
            s.push(i);
        }
        
        // 남아있는 인덱스는 자신보다 낮은 값이 없는, 즉 끝까지 가격이 떨어지지 않음
        while (!s.isEmpty()) {
            answer[s.peek()] = prices.length - s.peek() - 1;
            s.pop();
        }
        
        
        return answer;
    }
}