|
| 1 | +class StockPrice { |
| 2 | + Map<Integer, Integer> map; |
| 3 | + int mostRecentTimeStamp; |
| 4 | + PriorityQueue<int[]> minHeap; |
| 5 | + PriorityQueue<int[]> maxHeap; |
| 6 | + public StockPrice() { |
| 7 | + map = new HashMap<>(); |
| 8 | + mostRecentTimeStamp = Integer.MIN_VALUE; |
| 9 | + minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); |
| 10 | + maxHeap = new PriorityQueue<>((a, b) -> b[0] - a[0]); |
| 11 | + } |
| 12 | + |
| 13 | + public void update(int timestamp, int price) { |
| 14 | + map.put(timestamp, price); |
| 15 | + mostRecentTimeStamp = Math.max(mostRecentTimeStamp, timestamp); |
| 16 | + minHeap.add(new int[]{price, timestamp}); |
| 17 | + maxHeap.add(new int[]{price, timestamp}); |
| 18 | + } |
| 19 | + |
| 20 | + public int current() { |
| 21 | + return map.get(mostRecentTimeStamp); |
| 22 | + } |
| 23 | + |
| 24 | + public int maximum() { |
| 25 | + return getUpdatedValueFromHeap(maxHeap); |
| 26 | + } |
| 27 | + |
| 28 | + public int minimum() { |
| 29 | + return getUpdatedValueFromHeap(minHeap); |
| 30 | + } |
| 31 | + |
| 32 | + private int getUpdatedValueFromHeap(PriorityQueue<int[]> heap) { |
| 33 | + int[] entry = heap.poll(); |
| 34 | + while (entry[0] != map.get(entry[1])) { |
| 35 | + entry = heap.poll(); |
| 36 | + } |
| 37 | + heap.add(entry); |
| 38 | + return entry[0]; |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +/** |
| 43 | + * Your StockPrice object will be instantiated and called as such: |
| 44 | + * StockPrice obj = new StockPrice(); |
| 45 | + * obj.update(timestamp,price); |
| 46 | + * int param_2 = obj.current(); |
| 47 | + * int param_3 = obj.maximum(); |
| 48 | + * int param_4 = obj.minimum(); |
| 49 | + */ |
0 commit comments