Stock Price Fluctuation — LeetCode 2034 Python Solution
MediumDesignHash TableData StreamOrdered SetHeap (Priority Queue)
- Problem
- #2034
- Pattern
- Heap / Priority Queue
- Reading time
- 6 min
- Source
- leetcode.com
The 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.
Example
- Input
- ["StockPrice", "update", "update", "current", "maximum", "update", "maximum", "update", "minimum"]
- Output
- [null, null, null, 5, 10, null, 5, null, 2]
- Explanation
- StockPrice stockPrice = new StockPrice();
Python solution
Python
class StockPrice:
def __init__(self):
self.d = {}
self.ls = SortedList()
self.last = 0
def update(self, timestamp: int, price: int) -> None:
if timestamp in self.d:
self.ls.remove(self.d[timestamp])
self.d[timestamp] = price
self.ls.add(price)
self.last = max(self.last, timestamp)
def current(self) -> int:
return self.d[self.last]
def maximum(self) -> int:
return self.ls[-1]
def minimum(self) -> int:
return self.ls[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()Complexity
| Measure | Complexity |
|---|---|
| Time | O(log n) |
| Space | O(n), where n is the number of `update` operations auxiliary |
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2034. Stock Price Fluctuation is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2034. Stock Price Fluctuation?
- LeetCode 2034. Stock Price Fluctuation is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2034. Stock Price Fluctuation?
- The Python solution on this page runs in O(log n).
- What is the space complexity of LeetCode 2034. Stock Price Fluctuation?
- The Python solution on this page uses O(n), where n is the number of `update` operations auxiliary space.
- What topics does LeetCode 2034. Stock Price Fluctuation cover?
- LeetCode 2034. Stock Price Fluctuation is tagged Design, Hash Table, Data Stream, Ordered Set and Heap (Priority Queue) on LeetCode.