알고리즘/스택 큐

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

연향동큰손 2025. 3. 12. 13:50

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

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

알고리즘 고득점 Kit에 스택/큐로 분류 되어있어서 계속 고민하다가 스택큐가 아닌 배열로 풀 수 있을 것 같아서 배열로 풀어봤다.

 

prices 배열을 순회하면서 현재 위치 뒤의 요소들과 크기를 비교하여, 주식 가격이 유지되는 시간을 결정하고

time 변수를 큐에 저장하고 answer 배열로 이동시켜서 출력했다.

 

※주의할 점

  • 현재 위치의 다음 위치에서 바로 주식 가격이 떨어져도 1초 동안 가격이 유지 된것으로 간주한다!

 

즉 반목문을 작성할때 가격의 크기 비교를 하기전에 time ++을 하여 1초동안 가격이 유지된 것으로 만들어줘야 한다.

for(int i=0; i<prices.length; i++){
            int n = prices[i];
            int time = 0;
            if(i!=prices.length-1){
            for(int j=i+1; j<prices.length; j++){
                time++; //시간 증가!
                if(n>prices[j]){
                    break;
                }
            }
        }
            queue.add(time);
        }

 

 


 

<전체 코드>

 

import java.util.*;

class Solution {
    public int[] solution(int[] prices) {
        int[] answer = {};
        Queue<Integer> queue = new LinkedList<>();
        
        for(int i=0; i<prices.length; i++){
            int n = prices[i];
            int time = 0;
            if(i!=prices.length-1){
            for(int j=i+1; j<prices.length; j++){
                time++;
                if(n>prices[j]){
                    break;
                }
            }
        }
            queue.add(time);
        }
        
        int size = queue.size();
        answer=new int[size];
        for(int i=0; i<size; i++){
            answer[i]=queue.poll();
        }
        
        return answer;
    }
}