What is Stock Span
The span of a day is how many consecutive days, ending today, have a price less than or equal to today's price.
Approach
Visualization & algorithm
The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each day is pushed and popped once. |
| Space | O(n) | A strictly falling price list fills the stack. |
Implementation
def solve(self, prices):
st, ans = [], []
for i, p in enumerate(prices):
while st and prices[st[-1]] <= p:
st.pop()
ans.append(i + 1 if not st else i - st[-1])
st.append(i)
return ans