Java/알고리즘

주식 가격

티코딩 2023. 11. 21. 10:11

문제를 처음 보고 설명이 이게 단가? 했다. 뭔소린가했더니 첫1초 가격 1일때, 나머지 네번중에 1보다 작은가격은 없으니 떨어지지 않은것이므로 4, 2초일때 가격 2도 마찬가지로 나머지 세번중에 작은가격이 없으니 3 이런식이다. 그래서 스택으로 풀려다 큐로도 풀수 있을거같아서 큐로 풀었다.

ㅇ 1트

public static int[] solution(int[] prices) {
        int[] answer = {prices.length};
        Queue<Integer> priceQueue = new LinkedList<>();

        for(int price : prices){
            priceQueue.add(price);
        }
        int num = 0;
        //peek == 맨앞에있는거 반환
        //poll == 맨앞에있는거 반환하고 삭제
        while(priceQueue.peek() != null){
            int value = priceQueue.poll();
            answer[num] = 0;

            for(int price : priceQueue){
                answer[num]++;
                if(value > price){
                    break;
                }
            }
            num++;
        }
        return answer;
    }

분명 내 머리속으로 해봐도 맞고, 노트에 풀어봤을때도 이게 맞는데 ArraysIndexOutOfBounds 예외가 나오길래 뭐가 잘못된거지 한참을 보다가

answer의 길이를 초기화해야하는데, answer에다가 값을 넣어버린것이다...

진짜 너무 허무했다.

ㅇ 2트

public static int[] solution(int[] prices) {
        int[] answer = new int[prices.length];
        Queue<Integer> priceQueue = new LinkedList<>();

        for(int price : prices){
            priceQueue.add(price);
        }
        int num = 0;
        //peek == 맨앞에있는거 반환
        //poll == 맨앞에있는거 반환하고 삭제
        while(priceQueue.peek() != null){
            int value = priceQueue.poll();
            answer[num] = 0;

            for(int price : priceQueue){
                answer[num]++;
                if(value > price){
                    break;
                }
            }
            num++;
        }
        return answer;
    }

이렇게 하니깐 잘 됐다ㅋㅋㅋㅋ

진짜...오래간만에 풀었더니 배열 길이 초기화도 까먹은건가? 반성하자...