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

allnight5·2023년 7월 3일
0

프로그래머스

목록 보기
71/73

큐로 하려면
맨 뒤나 맨 앞부터 들어 있는 모든 것을
확인해야 하는데.. 그럼 2중 반복문과 같다.

2중 반복문

import java.util.Stack; 
class Solution {
    public int[] solution(int[] prices) {
        int endPoint = prices.length;
        int[] answer = new int[endPoint];
        for(int i=0; i<endPoint;i++){
            for(int j=i+1; j<endPoint; j++){
                answer[i]++;
                if(prices[i] > prices[j]){
                    break;
                }
            } 
        }
        return answer;        
    }
}

stack

import java.util.Stack;

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

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

        while (!stack.isEmpty()) {
            int idx = stack.pop();
            answer[idx] = endPoint - 1 - idx;
        }

        return answer;
    }
}
profile
공부기록하기

0개의 댓글