Online Stock Span
Design a class that collects daily stock prices and returns the span — the number of consecutive days (including today) the price was <= today's price.
Example: prices = [100,80,60,70,60,75,85] → spans = [1,1,1,2,1,4,6]
Sample Input
—
Sample Output
—
Constraints
- 1 <= price <= 10^5
- At most 10^4 calls to next
Topics
Monotonic Stack
class StockSpanner {
constructor() { this.stack = []; }
next(price) {
let span = 1;
while (this.stack.length && this.stack[this.stack.length-1][0] <= price)
span += this.stack.pop()[1];
this.stack.push([price, span]);
return span;
}
}
Time: O(1) amortized | Space: O(n)
Saved in this browser only. Private to you.