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
s = StockSpanner()
assert [s.next(p) for p in [100, 80, 60, 70, 60, 75, 85]] == [1, 1, 1, 2, 1, 4, 6]
s2 = StockSpanner()
assert [s2.next(p) for p in [31, 41, 48, 59, 79]] == [1, 2, 3, 4, 5]
class StockSpanner {
private final Deque<int[]> st = new ArrayDeque<>(); // {price, span}
public int next(int price) {
int span = 1;
while (!st.isEmpty() && st.peek()[0] <= price) span += st.pop()[1];
st.push(new int[]{price, span});
return span;
}
}
type StockSpanner struct {
st [][2]int // (price, span)
}
func Constructor() StockSpanner {
return StockSpanner{}
}
func (this *StockSpanner) Next(price int) int {
span := 1
for n := len(this.st); n > 0 && this.st[n-1][0] <= price; n = len(this.st) {
span += this.st[n-1][1]
this.st = this.st[:n-1]
}
this.st = append(this.st, [2]int{price, span})
return span
}