You are given an array prices where prices[i] is the price of a stock on day i. Compute the stock span for every day.
The stock span of day i is the largest number of consecutive days, ending at day i and counting backwards, on which the price was less than or equal to prices[i]. Day i itself always counts, so every span is at least 1.
Return an array spans of the same length, where spans[i] is the stock span of day i.
Function Signature
def calculate_span(prices: list[int]) -> list[int]:
Rules
-
An earlier day whose price equals
prices[i]
counts toward the span of day
i
.
-
The backward run stops at the first earlier day whose price is strictly greater than
prices[i]
. If there is no such day, the span of day
i
is
i + 1
.
Constraints
-
1 <= len(prices) <= 10^5
-
1 <= prices[i] <= 10^5
Examples
Input: prices = [100, 80, 60, 70, 60, 75, 85]
Output: [1, 1, 1, 2, 1, 4, 6]
Days 0, 1, 2 and 4 each come right after a higher price, so their span is 1. Day 3 (70) covers the 60 before it and stops at 80, giving 2. Day 5 (75) covers 60, 70 and 60 and stops at 80, giving 4. Day 6 (85) covers everything back to 80 and stops at 100, giving 6.
Input: prices = [10, 4, 5, 90, 120, 80]
Output: [1, 1, 2, 4, 5, 1]
Day 2 (5) covers the 4 before it and stops at 10. Day 3 (90) is at least every earlier price, so its span is all four days 0 to 3, and day 4 (120) covers all five days. Day 5 (80) comes right after 120, so its span is 1.
Input: prices = [3, 3, 1, 3]
Output: [1, 2, 1, 4]
Equal prices extend the span. Day 1 counts day 0 because both are 3, and day 3 counts 1, 3 and 3 before it, so it reaches back to day 0.