SDE & MLE Prep

901. Online Stock Span

Problem

Design StockSpanner, whose next(price) receives a stock's daily price and returns its span: how many consecutive days, ending today and going back, had a price ≤ today's.

Example: prices 100, 80, 60, 70, 60, 75, 85 → spans 1, 1, 1, 2, 1, 4, 6

Constraints: up to 10⁴ calls.

Stack of (price, span) with decreasing prices. A new price absorbs (pops) all smaller-or-equal prices and adds their spans.

Complexity: amortized O(1) per call.

class StockSpanner:
    def __init__(self):
        self.st = []  # (price, span)

    def next(self, price: int) -> int:
        span = 1
        while self.st and self.st[-1][0] <= price:
            span += self.st.pop()[1]
        self.st.append((price, span))
        return span