Online Stock Span
Difficulty: Medium · Pattern: Stack & Monotonic Stack · LeetCode #901
Design StockSpanner. Each call next(price) returns today's span: the number of consecutive days, ending today and going backwards, on which the price was ≤ today's price.
Example
text
next(100) → 1, next(80) → 1, next(60) → 1, next(70) → 2, next(60) → 1, next(75) → 4, next(85) → 6Hints
- Earlier days with lower prices are "absorbed" into today's span forever.
- Keep a stack of (price, span) pairs with strictly decreasing prices.
Approach
For a new price, start span = 1; while the stack top's price ≤ price, pop it and add its span. Push (price, span) and return the span. Each day is pushed and popped at most once, so the amortized cost is O(1) per call.
Complexity
Time: O(1) amortized per call. Space: O(n).
Python solution
class StockSpanner:
def __init__(self):
self.st = []
def next(self, price):
span = 1
while self.st and self.st[-1][0] <= price:
span += self.st.pop()[1]
self.st.append((price, span))
return spanJavaScript solution
class StockSpanner {
constructor() { this.st = []; }
next(price) {
let span = 1;
while (this.st.length && this.st[this.st.length - 1][0] <= price) span += this.st.pop()[1];
this.st.push([price, span]);
return span;
}
}