2034. Stock Price Fluctuation
T: O(nlogn), O(1), O(1), O(1)
S: O(n)
class StockPrice {
private Map<Integer, Integer> timeMap;
private TreeMap<Integer, Set<Integer>> priceMap;
private int latestTime;
public StockPrice() {
this.timeMap = new HashMap<>();
this.priceMap = new TreeMap<>();
}
// O(logn) -> call n times, so O(nlogn)
public void update(int timestamp, int price) {
if (timeMap.containsKey(timestamp)) {
int prevPrice = timeMap.get(timestamp);
priceMap.get(prevPrice).remove(timestamp);
if (priceMap.get(prevPrice).isEmpty()) {
priceMap.remove(prevPrice);
}
}
timeMap.put(timestamp, price);
priceMap.computeIfAbsent(price, k -> new HashSet<>()).add(timestamp);
latestTime = Math.max(latestTime, timestamp);
}
// O(1)
public int current() {
return timeMap.get(latestTime);
}
// O(1)
public int maximum() {
return priceMap.lastKey();
}
// O(1)
public int minimum() {
return priceMap.firstKey();
}
}
/**
* Your StockPrice object will be instantiated and called as such:
* StockPrice obj = new StockPrice();
* obj.update(timestamp,price);
* int param_2 = obj.current();
* int param_3 = obj.maximum();
* int param_4 = obj.minimum();
latest price -> use variable or
timestamp, int price
if update timestamp-> use price to find List<Time> -> remove that time, if list empty -> remove price
-> add price, List<time>
price use treeMap
*/notice this Question just aims for a particular stock
S: O(n), n is num of stocks
Last updated
Was this helpful?