본문 바로가기
Java/Programmers

Stack/Queue - Level 2, 주식가격

by GLOWWW 2021. 1. 14.

어렵다..난 이렇게밖에 못하겟던데.. 스택이나 큐를 이용해서 풀어야한다..

import java.util.*;

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

그래서 다른분의 풀이를 찾아봄 Queue를 사용하여 푸셨당.

class Solution {
    public int[] solution(int[] prices) {
        int[] answer = new int[prices.length];

        Queue<Integer> q = new LinkedList<>();
        // 주식 가격 queue에 넣기
        for(int i=0; i<prices.length; i++){
            q.offer(prices[i]);
        }

        //peek()에서 prices들과 가격 비교 time ++
        int idx = 0;
        int time = 0;
        while(!q.isEmpty()){
            time = 0;
            for(int i=idx+1; i<prices.length; i++){
                if(q.peek() <= prices[i]){
                    time++;
                }
                else{
                    time++;
                    break;
                }
            }
            q.poll();
            answer[idx] = time;
            idx ++;
        }

        return answer;
    }
}

출처: Developer YU님 페이지로 이동!

'Java > Programmers' 카테고리의 다른 글

[Lv.0]캐릭터의 좌표  (0) 2023.01.17
[Lv.0]삼각형의 완성조건(2)  (0) 2023.01.17
Hash - Level 2, 위장  (0) 2021.01.13
Hash - Level2, 전화번호 목록  (0) 2021.01.13
Hash - Level 1, 완주하지 못한 선수  (0) 2021.01.12

댓글