최대 1 분 소요

문제 바로가기

JAVA

이중반복문을 이용한 풀이

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

스택/큐를 이용한 풀이

스택/큐를 이용하는 방법을 모르겠어서, 다른 분의 풀이를 참고했다.
참고한 블로그

스택에 대해 더 공부하고 싶어서 블로그를 찾아봤다.
스택

import java.util.Stack;

class Solution {
    public int[] solution(int[] prices) {
        int leng = prices.length;
        int[] answer = new int[leng];
        Stack<Integer>stack = new Stack();
        for(int i=0;i<leng;i++){
            while(!stack.isEmpty() && prices[i] < prices[stack.peek()]){
                answer[stack.peek()] = i-stack.peek();
                stack.pop();
            }
            stack.push(i);
        }


        while(!stack.isEmpty()){
            // 배열 끝까지 주식가격이 떨어지지 않았다면
            // 반복문을 다 돌았음에도 불구하고
            // 스택에 값이 남아있다.
             answer[stack.peek()] = leng-stack.peek()-1;
             stack.pop();
        }

        return answer;
    }
}


회고하기

큐도 공부하면 좋겠다.

댓글남기기