You are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp.
Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same timestamp may appear later in the stream correcting the price of the previous wrong record.
Design an algorithm that:
Implement the StockPrice class:
StockPrice() Initializes the object with no price records.void update(int timestamp, int price) Updates the price of the stock at the given timestamp.int current() Returns the latest price of the stock.int maximum() Returns the maximum price of the stock.int minimum() Returns the minimum price of the stock.Input
["StockPrice", "update", "update", "current", "maximum", "update", "maximum", "update", "minimum"]
[[], [1, 10], [2, 5], [], [], [1, 3], [], [4, 2], []]
Output
[null, null, null, 5, 10, null, 5, null, 2]
Explanation
update, current, maximum, and minimum.current, maximum, and minimum will be called only after update has been called at least once.The brute force approach is fairly straightforward. We maintain a list of pairs and simply update or query the list as required. This approach will straightforwardly tackle the problem but will have inefficiencies especially given the constraints.
update: O(n) where n is the number of prices, as we might need to traverse the entire list to update a price.current: O(n) to find the current price matching the maximum timestamp.maximum and minimum: O(n) each to find the maximum and minimum prices.Using a HashMap allows for more efficient updates. By keeping track of the prices with their timestamps in a map, the update and current operations become more efficient. However, we still need list-like structures to calculate max and min in a straightforward method or employ further structures to maintain these values efficiently.
update and current: O(1) due to HashMap operations.maximum and minimum: O(n) because we still have to possibly traverse all prices.TreeMap inherently sorts its keys, providing a way to efficiently find min and max along with an easy way to get the current price using the highest timestamp. This allows all operations to be more efficient except adding or removing, which are logarithmic due to the properties of the TreeMap.
update: O(log n) for both adding the new timestamp-price pair and updating counting in the count map.current: O(1) using TreeMap's floor function.maximum and minimum: O(1) to directly access the max and min keys in the count TreeMap.