|
1 | 1 | import java.util.*; |
| 2 | + |
2 | 3 | class Solution { |
3 | | - class Status{ |
| 4 | + class Stock { |
| 5 | + private int time; |
4 | 6 | private int price; |
5 | | - private int idx; |
6 | 7 |
|
7 | | - public Status(int price, int idx){ |
| 8 | + public Stock(int price, int time) { |
8 | 9 | this.price = price; |
9 | | - this.idx = idx; |
10 | | - } |
11 | | - |
12 | | - @Override |
13 | | - public String toString(){ |
14 | | - return "[" + this.price + "," + this.idx +"]"; |
| 10 | + this.time = time; |
15 | 11 | } |
16 | 12 | } |
17 | 13 |
|
18 | 14 | public int[] solution(int[] prices) { |
19 | | - Stack<Status> stack = new Stack<>(); |
20 | | - int len = prices.length; |
21 | | - int[] answer = new int[len]; |
| 15 | + Stack<Stock> stack = new Stack<>(); |
| 16 | + int[] answer = new int[prices.length]; |
22 | 17 |
|
23 | | - for(int i =0; i < len ; i++){ |
24 | | - int price = prices[i]; |
25 | | - Status status = new Status(price,i); |
26 | | - if(stack.isEmpty()){ |
27 | | - stack.push(status); |
28 | | - } else { |
29 | | - while(true) { |
30 | | - if(stack.isEmpty()){ |
31 | | - stack.push(status); // 추가 |
32 | | - break; |
33 | | - } |
34 | | - Status storedStaus = stack.peek(); |
35 | | - int storedPrice = storedStaus.price; |
36 | | - int storedIdx = storedStaus.idx; |
37 | | - |
38 | | - // 새로운 값이 더 작을 때 |
39 | | - if(storedPrice > price) { |
40 | | - answer[storedIdx] = i - storedIdx; |
41 | | - stack.pop(); // 제거 |
42 | | - } else{ |
43 | | - stack.push(status); // 추가 |
44 | | - break; |
45 | | - } |
46 | | - } |
| 18 | + for(int currentTime = 0; currentTime < prices.length; currentTime ++) { |
| 19 | + int price = prices[currentTime]; |
| 20 | + |
| 21 | + while(!stack.isEmpty()) { |
| 22 | + // 가격이 떨어졌다면 |
| 23 | + if(stack.peek().price > price){ |
| 24 | + Stock stock = stack.pop(); |
| 25 | + answer[stock.time] = currentTime - stock.time; |
| 26 | + } else break; |
47 | 27 | } |
| 28 | + stack.push(new Stock(price,currentTime)); |
48 | 29 | } |
49 | 30 |
|
50 | | - // 찌꺼기 처리 |
51 | | - while(!stack.isEmpty()){ |
52 | | - Status storedStaus = stack.pop(); |
53 | | - int storedPrice = storedStaus.price; |
54 | | - int storedIdx = storedStaus.idx; |
55 | | - |
56 | | - answer[storedIdx] = len - 1 - storedIdx; |
| 31 | + |
| 32 | + while(!stack.isEmpty()) { |
| 33 | + Stock stock = stack.pop(); |
| 34 | + answer[stock.time] = prices.length - 1 - stock.time; |
57 | 35 | } |
58 | 36 |
|
59 | 37 | return answer; |
|
0 commit comments