Stock Price Fluctuation Problem
#2034
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2034.
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 thepriceof 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.
Example 1:
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
StockPrice stockPrice = new StockPrice();
stockPrice.update(1, 10); // Timestamps are [1] with corresponding prices [10].
stockPrice.update(2, 5); // Timestamps are [1,2] with corresponding prices [10,5].
stockPrice.current(); // return 5, the latest timestamp is 2 with the price being 5.
stockPrice.maximum(); // return 10, the maximum price is 10 at timestamp 1.
stockPrice.update(1, 3); // The previous timestamp 1 had the wrong price, so it is updated to 3.
// Timestamps are [1,2] with corresponding prices [3,5].
stockPrice.maximum(); // return 5, the maximum price is 5 after the correction.
stockPrice.update(4, 2); // Timestamps are [1,2,4] with corresponding prices [3,5,2].
stockPrice.minimum(); // return 2, the minimum price is 2 at timestamp 4.
Constraints:
1 <= timestamp, price <= 10^9- At most
10^5calls will be made in total toupdate,current,maximum, andminimum. current,maximum, andminimumwill be called only afterupdatehas been called at least once.
Solution
Approach: Hash table + sorted multiset of prices
Keep these pieces of state:
d: a hash table from timestamp to its current price;- a sorted multiset of all current prices (a
TreeMapormultiset; where the language has none, as in Python, JavaScript and Go, two heaps with lazy deletion do the same job); last: the latest timestamp seen so far.
The operations are:
update(timestamp, price): if the timestamp already has a price, that old price is removed from the multiset first (with heaps, it is simply left there as a stale entry). Then store the new price indand in the multiset, and setlast = max(last, timestamp).current(): returnd[last].maximum()andminimum(): read the largest or smallest price of the multiset. With heaps, first pop the top entries whose price no longer matchesd[timestamp].
Each operation takes O(log n) time (amortized for the heaps) except current, which takes O(1). The space complexity is O(n), where n is the number of update calls.
import heapq
class StockPrice:
def __init__(self):
self.d = {}
self.mx = []
self.mn = []
self.last = 0
def update(self, timestamp: int, price: int) -> None:
self.d[timestamp] = price
heapq.heappush(self.mx, (-price, timestamp))
heapq.heappush(self.mn, (price, timestamp))
self.last = max(self.last, timestamp)
def current(self) -> int:
return self.d[self.last]
def maximum(self) -> int:
while self.d[self.mx[0][1]] != -self.mx[0][0]:
heapq.heappop(self.mx)
return -self.mx[0][0]
def minimum(self) -> int:
while self.d[self.mn[0][1]] != self.mn[0][0]:
heapq.heappop(self.mn)
return self.mn[0][0]
# Your StockPrice object will be instantiated and called as such:
# obj = StockPrice()
# obj.update(timestamp,price)
# param_2 = obj.current()
# param_3 = obj.maximum()
# param_4 = obj.minimum()