티스토리 뷰

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

 

코딩테스트 연습 - 주식가격

초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요. 제한사항 prices의 각 가격은 1 이상 10,00

programmers.co.kr

풀이법: 그냥 기본 배열 문제

Comment:

1) 어떤 조건이 더 많은 상황을 cover하는지 잘 생각해보자.

2) 처음엔 if(prices[i] <= prices[j]) count++; 로 했다. 이렇게 하면 무조건 n^2 번 돌게 된다. 문제 조건을 잘 보면 크면 prices[i] > prices[j]가 되는 순간 나머지 배열을 볼 필요가 없다.

3) 이게 왜 스택/큐?

 

class Solution {
    public int[] solution(int[] prices) {

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

    }
}