Online Stock Span
1 approach, code in every language
Problem description
Design an algorithm that computes the span of a stock's daily price as new prices stream in one at a time.
The span of the current day is the number of consecutive days ending with today (including today) for which the price was less than or equal to today's price.
Implement the `StockSpanner` class:
- `StockSpanner()` initializes the object. - `next(price)` records today's `price` and returns the span for that day.
Example 1
Input: StockSpanner(); next(100); next(80); next(60); next(70); next(60); next(75); next(85)
Output: [1, 1, 1, 2, 1, 4, 6]
70 covers itself and the prior 60 (span 2). 75 covers 60, 70, 60 and itself (span 4). 85 covers all of 80, 60, 70, 60, 75 and itself (span 6).
Example 2
Input: StockSpanner(); next(31); next(41); next(48); next(59); next(26)
Output: [1, 2, 3, 4, 1]
Each rising price extends the run: 41 spans 2, 48 spans 3, 59 spans 4. The drop to 26 resets the span to 1.
Constraints
1 <= price <= 10^5At most 10^4 calls will be made to next.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free