Medium
088Online Stock Span
Given daily prices, return the stock span for each day.
EXAMPLES
Example 1
Input
{
"prices": [
100,
80,
60,
70,
60,
75,
85
]
}
Output
[
1,
1,
1,
2,
1,
4,
6
]FUNCTION SHAPE
prices: intArray→intArraySOLUTION NOTE
Dynamic NGE template. Store (price, span_value) pairs to save redundant work.
Reveal reference solution +
pythonREFERENCE
class StockSpanner:
def __init__(self):
self.stack = []
def next(self, price: int) -> int:
ans = 1
while self.stack and self.stack[-1][0] <= price:
ans += self.stack.pop()[1]
self.stack.append((price, ans))
return ansTime
O(n) amortizedSpace
O(n)