Track the span of consecutive lower-or-equal price days using a monotonic stack.
Design a class `StockSpanner` 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 the stock over the last 4 days was `[7, 34, 1, 2]` and the price today is `8`, then the span is 3 because starting from today, the price was `2, 1, 34` (all <= 8), but not `7` (since 7 <= 8? Actually 7 <= 8, so that would make span 4. Wait, carefully: The definition says going backward from today, the span counts consecutive days where price <= today's price. The sequence is [7, 34, 1, 2, 8] today. Going back: 8, 2, 1, 34, 7. We stop at the first day that breaks the condition, i.e., price > today. Here 34 > 8, so we stop before 34. So the count is 3 (today, 2, 1). Note: 34 > 8 breaks it, so we don't include 7. Important: The condition is price <= current price, so 34 > 8 breaks, so span = 3.
You are to implement:
- `__init__(self)` – initializes the spanner.
- `next(self, price: int) -> int` – records the price for today and returns the span.
Additionally, provide a top-level helper function `def StockSpanner_next_sequence(prices: List[int]) -> List[int]:` that runs the sequence of prices through a fresh `StockSpanner` and returns the spans as a list.
You must handle the stream efficiently. The total number of calls to `next` will be at most 10^5.
**Constraints:**
- 1 <= price <= 10^5
- At most 10^5 calls to `next`.
- Total time complexity for all calls should be O(n) amortized.
Constraints
1 <= price <= 10^5
At most 10^5 calls to `next`.
Total time complexity across all calls must be O(n) amortized.
Example
>>> sp = StockSpanner()
>>> sp.next(100) # returns 1
1
>>> sp.next(80) # returns 1
1
>>> sp.next(60) # returns 1
1
>>> sp.next(70) # returns 2
2
>>> sp.next(60) # returns 1
1
>>> sp.next(75) # returns 4
4
>>> sp.next(85) # returns 6
6
>>> StockSpanner_next_sequence([100, 80, 60, 70, 60, 75, 85])
[1, 1, 1, 2, 1, 4, 6]
20 points
~25 min