프로그래머스 - 주식가격(Level 2)

2024. 2. 20. 18:30코딩테스트 정리(자바)

728x90

스택 쓰지 않고 풀이

import java.util.*;
class Solution {
    public int[] solution(int[] prices) {
        int[] answer = new int[prices.length];
        Arrays.fill(answer,0);
        
        for(int i=0;i<prices.length;i++){
            int cnt=0;
            for(int j=i+1;j<prices.length;j++){
                if(prices[i]<=prices[j])
                    cnt++;
                else{
                    cnt++;
                    break;
                }    
            }
           answer[i]=cnt;
        }
        return answer;
    }
}

 


 

스택이용해서 풀이

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

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

            stack.push(i); //인덱스를 넣음
        }

        while (!stack.isEmpty()) {
            int index = stack.pop();
            answer[index] = prices.length - index - 1;
        }
        return answer;
    }
}

 

 

잘 이해가 안 가서 블로그 참고

https://velog.io/@imok-_/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EC%A3%BC%EC%8B%9D%EA%B0%80%EA%B2%A9-java-Stack-%ED%99%9C%EC%9A%A9

728x90