Online Stock Span - Problem
Design an algorithm 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 in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day.
For example:
- If the prices in the last four days were
[7,2,1,2]and today's price is2, then the span is4because all 4 consecutive days had prices ≤ 2. - If the prices in the last four days were
[7,34,1,2]and today's price is8, then the span is3because the last 3 days had prices ≤ 8 (but day 4 had price 34 > 8).
Implement the StockSpanner class:
StockSpanner()Initializes the objectint next(int price)Returns the span of the stock's price given that today's price is price
Input & Output
Example 1 — Basic Stock Prices
$
Input:
prices = [100,80,60,70,60,75,85]
›
Output:
[1,1,1,2,1,4,6]
💡 Note:
Day 1: price=100, span=1 (just today). Day 2: price=80, span=1 (80<100). Day 3: price=60, span=1 (60<80). Day 4: price=70, span=2 (70≥60, 70<80). Day 5: price=60, span=1 (60<70). Day 6: price=75, span=4 (75≥60,70,60, 75<80). Day 7: price=85, span=6 (85≥75,60,70,60,80, 85<100).
Example 2 — Increasing Prices
$
Input:
prices = [10,20,30,40]
›
Output:
[1,2,3,4]
💡 Note:
Each day has a higher price, so the span includes all previous days plus today.
Example 3 — Decreasing Prices
$
Input:
prices = [40,30,20,10]
›
Output:
[1,1,1,1]
💡 Note:
Each day has a lower price than the previous, so span is always 1 (just today).
Constraints
- 1 ≤ prices.length ≤ 104
- 1 ≤ prices[i] ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input
Stream of daily stock prices: [100,80,60,70,60,75,85]
2
Process
For each price, count consecutive days ≤ current price
3
Output
Spans: [1,1,1,2,1,4,6]
Key Takeaway
🎯 Key Insight: Use a monotonic stack to skip irrelevant days and achieve O(1) amortized time per query
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code