Online Stock Span Problem
Description
LeetCode Problem 901.
Design an algorithm that collects daily price quotes for some stock and returns the span of that stock's price for the current day.
The span of the stock's price today is defined as the maximum number of consecutive days (starting from today and going backward) for which the stock price was less than or equal to today's price.
- For example, if the price of a stock over the next 7 days were [100,80,60,70,60,75,85], then the stock spans would be [1,1,1,2,1,4,6].
Implement the StockSpanner class:
- StockSpanner() Initializes the object of the class.
- int next(int price) Returns the span of the stock's price given that today's price is price.
Example 1:
Input
["StockSpanner", "next", "next", "next", "next", "next", "next", "next"]
[[], [100], [80], [60], [70], [60], [75], [85]]
Output
[null, 1, 1, 1, 2, 1, 4, 6]
Explanation
StockSpanner stockSpanner = new StockSpanner();
stockSpanner.next(100); // return 1
stockSpanner.next(80); // return 1
stockSpanner.next(60); // return 1
stockSpanner.next(70); // return 2
stockSpanner.next(60); // return 1
stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.
stockSpanner.next(85); // return 6
Constraints:
- 1 <= price <= 10^5
- At most 10^4 calls will be made to next.
Solution
Approach: Monotonic Stack of (Price, Span)
Scanning backward from today on every call takes O(n) per call, and O(n2) in total when prices keep falling and then jump. The fix is to remember, for each kept day, how many days it already covers.
Keep a stack of (price, span) pairs whose prices strictly decrease from bottom to top. For next(price):
- Start with
span = 1for today. - While the top of the stack has a price
<= price, pop it and add its span tospan. Every day that the popped day covered was at most its price, so it is also at most today's price. - Push
(price, span)and returnspan.
A popped day is never needed again: today's price is at least as high and today is more recent, so any later day that reaches the popped day will first reach today and absorb it through today's span. The loop stops at the first higher price, which is exactly where the run of lower-or-equal prices ends.
Use <=, not <: equal prices count toward the span.
For the example, when 75 arrives the stack is (100,1) (80,1) (70,2) (60,1). It pops (60,1) and (70,2), giving span 1 + 1 + 2 = 4. Then 85 pops (75,4) and (80,1), giving 6.
Complexity: O(1) amortized time per call, since each price is pushed once and popped at most once. O(n) space, where n is the number of calls.
class StockSpanner:
def __init__(self):
# (price, span) pairs with strictly decreasing prices from bottom to top.
self.stack = []
def next(self, price: int) -> int:
span = 1 # today
# Every day covered by a lower-or-equal price is also covered by today.
while self.stack and self.stack[-1][0] <= price:
span += self.stack.pop()[1]
self.stack.append((price, span))
return span
Now write it from memory
Close the write-up and solve it yourself against the tests.