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 on one day is the maximum number of consecutive days, starting from that day and going backward, on which the stock price was less than or equal to the price of that day.
For example, if the prices of the stock over the last four days are [7, 2, 1, 2] and today's price is 2, the span of today is 4: starting from today, the price was less than or equal to 2 for 4 consecutive days.
If the prices over the last four days are [7, 34, 1, 2] and today's price is 8, the span of today is 3: starting from today, the price was less than or equal to 8 for 3 consecutive days.
Implement the StockSpanner class:
-
StockSpanner()
initializes the object.
-
next(price)
records today's price as
price
and returns the span of that price.
Function Signature
class StockSpanner:
def __init__(self) -> None: ...
def next(self, price: int) -> int: ...
Rules
-
Calls to
next
arrive in day order, and the object keeps every earlier price across calls.
-
Today's own price counts, so every span is at least 1. Earlier days whose price equals today's price count toward the span.
-
Examples are written as a list of operation names and a matching list of argument lists. The output lists the return value of each operation in order, with
None
for the constructor.
Constraints
-
1 <= price <= 10^5
-
At most
10^4
calls are made to
next
.
Examples
Input: operations = ["StockSpanner", "next", "next", "next", "next", "next", "next", "next"], arguments = [[], [100], [80], [60], [70], [60], [75], [85]]
Output: [None, 1, 1, 1, 2, 1, 4, 6]
next(100), next(80) and next(60) each return 1 because the previous price is higher. next(70) covers 60 and itself, so it returns 2, and the following next(60) returns 1. next(75) covers 60, 70 and 60 and stops at 80, returning 4. next(85) covers 75, 60, 70, 60 and 80 and stops at 100, returning 6.
Input: operations = ["StockSpanner", "next", "next", "next"], arguments = [[], [31], [41], [48]]
Output: [None, 1, 2, 3]
The prices are strictly increasing, so each new price covers every day seen so far.
Input: operations = ["StockSpanner", "next", "next", "next", "next"], arguments = [[], [5], [5], [3], [5]]
Output: [None, 1, 2, 1, 4]
The second 5 counts the first one because equal prices qualify. The last 5 covers 3, 5 and 5 before it, so its span is all four days.