#2034
Stock Price Fluctuation
specialist · 885 · lc medium +31 · 48.9% accepted · 1,277 likes · top 35%
Description
You receive an out-of-order stream of (timestamp, price) records for a stock. Later records may correct earlier ones at the same timestamp. Design the StockPrice class with four operations:
- StockPrice() — constructor with no initial data.
- void update(int timestamp, int price) — record or correct the price at timestamp.
- int current() — return the price at the latest timestamp seen so far.
- int maximum() — return the highest price across all current records.
- int minimum() — return the lowest price across all current records.
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]
Example 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.
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24