Problem
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:
- Updates the price of the stock at a particular timestamp, correcting the price from any previous records at the timestamp.
- Finds the latest price of the stock based on the current records. The latest price is the price at the latest timestamp recorded.
- Finds the maximum price the stock has been based on the current records.
- Finds the minimum price the stock has been based on the current records.
Implement the StockPrice
class:
StockPrice()
Initializes the object with no price records.void update(int timestamp, int price)
Updates theprice
of the stock at the giventimestamp
.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.
Examples
Example 1
|
|
Constraints
1 <= timestamp, price <= 10^9
- At most
10^5
calls will be made in total toupdate
,current
,maximum
, andminimum
. current
,maximum
, andminimum
will be called only afterupdate
has been called at least once.
Solution
Method 1 - HashMap + Heaps (Priority Queues)
Intuition
We need to support fast updates, and fast queries for the latest, max, and min prices. Use a hashmap for timestamp→price, and two heaps (max-heap and min-heap) for price queries. When a price is updated, we may have stale entries in the heaps, so we lazily remove them when querying.
Approach
- Use a hashmap to store the latest price for each timestamp.
- Track the latest timestamp.
- Use a max-heap and min-heap to store (price, timestamp) pairs.
- For maximum/minimum, pop from the heap until the price matches the current price for that timestamp.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(log n)
per update/query (amortized, due to lazy deletion) - 🧺 Space complexity:
O(n)