알고리즘 풀이/프로그래머스
프로그래머스 - 주식가격 (스택/큐)
배게
2019. 12. 4. 09:09
728x90
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | public int[] solution(int[] prices) { int[] answer = new int[prices.length]; Stack<Integer> priceSt = new Stack<>(); Stack<Integer> indexSt = new Stack<>(); priceSt.push(prices[0]); indexSt.push(0); for (int i = 1; i < prices.length; i++) { while (true) { if (!priceSt.isEmpty() && priceSt.peek() > prices[i]) { int idx = indexSt.pop(); priceSt.pop(); answer[idx] = i - idx; } else break; } priceSt.push(prices[i]); indexSt.push(i); } while (!priceSt.isEmpty()) { int idx = indexSt.pop(); priceSt.pop(); answer[idx] = (prices.length - 1) - idx; } // for(int i : answer){ // System.out.println(i); // } return answer; } | cs |