[프로그래머스/큐] Level 2 주식가격 (JAVA)

Jiwoo Kim·2021년 2월 5일
0

알고리즘 정복하기

목록 보기
18/85
post-thumbnail

문제


1차 풀이 (2021.02.05)

  1. prices 배열을 차례대로 탐색하며 본인 이후의 가격 중 본인보다 적은 가격이 나타날 때까지 answer, 즉 기간을 증가시킨다.

코드

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

2차 풀이 (2021.08.26)

이전과 동일하게 풀었다.

코드

class Solution {
    public int[] solution(int[] prices) {
        int n = prices.length;
        
        int[] answer = new int[n];
        for (int before=0 ; before<n ; before++) {
            for (int after=before+1 ; after<n ; after++) {
                answer[before]++;
                if (prices[after] < prices[before]) {
                    break;
                }
            }
        }
        
        return answer;
    }
}

0개의 댓글