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
| class StockPrice {
private final TreeMap<Integer, Integer> timestampToPriceMap; private final TreeMap<Integer, Integer> priceToCountMap;
public StockPrice() { this.timestampToPriceMap = new TreeMap<>(); this.priceToCountMap = new TreeMap<>(); }
public void update(int timestamp, int price) { Integer prevPrice = timestampToPriceMap.put(timestamp, price); if (prevPrice != null) { int prevCount = priceToCountMap.get(prevPrice); if (prevCount == 1) { priceToCountMap.remove(prevPrice); } else { priceToCountMap.put(prevPrice, prevCount - 1); } } priceToCountMap.put(price, priceToCountMap.getOrDefault(price, 0) + 1); }
public int current() { return timestampToPriceMap.lastEntry().getValue(); }
public int maximum() { return priceToCountMap.lastKey(); }
public int minimum() { return priceToCountMap.firstKey(); }
}
|
References
2034. Stock Price Fluctuation