Stock Price Fluctuation
MEDIUMDescription
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 <= 109- At most
105calls will be made in total toupdate,current,maximum, andminimum. current,maximum, andminimumwill be called only afterupdatehas been called at least once.
Approaches
Checkout 3 different approaches to solve Stock Price Fluctuation . Click on different approaches to view the approach and algorithm in detail.
Optimized `current()` using TreeMap
This approach improves upon the brute-force method by using a TreeMap to store the timestamp-price data. A TreeMap keeps its keys (timestamps) sorted, which allows for efficient retrieval of the latest price, but finding the minimum and maximum prices still requires a full scan.
Algorithm
- Initialize a
TreeMap<Integer, Integer>to store timestamp-price records, which keeps them sorted by timestamp. - For
update(timestamp, price), usemap.put(timestamp, price). This takes O(log N) time. - For
current(), retrieve the last key (the maximum timestamp) from theTreeMapusinglastKey()and get its value. This takes O(log N) time. - For
maximum()andminimum(), iterate through all values in theTreeMap, which still takes O(N) time.
By replacing the HashMap with a TreeMap<Integer, Integer>, we can optimize the current() operation. A TreeMap is a sorted map that maintains its entries in ascending order of keys.
update(timestamp, price): We insert or update the key-value pair in theTreeMap. This operation takes O(log N) time, as the map needs to maintain its sorted order.current(): Since theTreeMapis sorted by timestamp, the latest timestamp is simply the last key in the map. We can retrieve this usingrecords.lastKey()in O(log N) time and then get its corresponding price.maximum(): To find the maximum price, we still need to iterate through all the values in theTreeMap. This remains an O(N) operation.minimum(): Similarly, finding the minimum price requires iterating through all values, taking O(N) time.
class StockPrice {
TreeMap<Integer, Integer> records;
public StockPrice() {
records = new TreeMap<>();
}
public void update(int timestamp, int price) {
records.put(timestamp, price);
}
public int current() {
// lastKey() gives the highest timestamp in O(log N)
return records.get(records.lastKey());
}
public int maximum() {
int maxPrice = 0;
for (int price : records.values()) {
maxPrice = Math.max(maxPrice, price);
}
return maxPrice;
}
public int minimum() {
int minPrice = Integer.MAX_VALUE;
for (int price : records.values()) {
minPrice = Math.min(minPrice, price);
}
return minPrice;
}
}
Complexity Analysis
Pros and Cons
- The
current()operation is significantly faster (O(log N)) than in the brute-force approach. - The implementation is still relatively simple.
- The
maximum()andminimum()operations remain inefficient with O(N) time complexity. - The
updateoperation is slightly slower (O(log N)) than the pureHashMapapproach (O(1)).
Code Solutions
Checking out 3 solutions in different languages for Stock Price Fluctuation . Click on different languages to view the code.
class StockPrice { private Map < Integer , Integer > d = new HashMap <>(); private TreeMap < Integer , Integer > ls = new TreeMap <>(); private int last ; public StockPrice () { } public void update ( int timestamp , int price ) { if ( d . containsKey ( timestamp )) { int old = d . get ( timestamp ); if ( ls . merge ( old , - 1 , Integer: : sum ) == 0 ) { ls . remove ( old ); } } d . put ( timestamp , price ); ls . merge ( price , 1 , Integer: : sum ); last = Math . max ( last , timestamp ); } public int current () { return d . get ( last ); } public int maximum () { return ls . lastKey (); } public int minimum () { return ls . 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(); */Video Solution
Watch the video walkthrough for Stock Price Fluctuation
Similar Questions
5 related questions you might find useful
Patterns:
Data Structures:
Companies:
Subscribe to Scale Engineer newsletter
Learn about System Design, Software Engineering, and interview experiences every week.
No spam, unsubscribe at any time.