Press "Enter" to skip to content

花花酱 LeetCode 901. Online Stock Span


Write a class StockSpanner which 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 today is defined as the maximum number of consecutive days (starting from today and going backwards) for which the price of the stock was less than or equal to today’s price.

For example, if the price of a stock over the next 7 days were [100, 80, 60, 70, 60, 75, 85], then the stock spans would be [1, 1, 1, 2, 1, 4, 6].

Example 1:

Input: ["StockSpanner","next","next","next","next","next","next","next"], [[],[100],[80],[60],[70],[60],[75],[85]]
Output: [null,1,1,1,2,1,4,6]
First, S = StockSpanner() is initialized.  Then: is called and returns 1, is called and returns 1, is called and returns 1, is called and returns 2, is called and returns 1, is called and returns 4, is called and returns 6.

Note that (for example) returned 4, because the last 4 prices
(including today's price of 75) were less than or equal to today's price.


  1. Calls to price) will have 1 <= price <= 10^5.
  2. There will be at most 10000 calls to per test case.
  3. There will be at most 150000 calls to across all test cases.
  4. The total time limit for this problem has been reduced by 75% for C++, and 50% for all other languages.


Solution 1: Brute Force (TLE)

Time complexity: O(n) per next call

Space complexity: O(n)

Solution 2: DP

dp[i] := span of prices[i]

j = i – 1
while j >= 0 and prices[i] >= prices[j]: j -= dp[j]
dp[i] = i – j


Solution 3: Monotonic Stack

Maintain a monotonic stack whose element are pairs of <price, span>, sorted by price from high to low.

When a new price comes in

  1. If it’s less than top price, add a new pair (price, 1) to the stack, return 1
  2. If it’s greater than top element, collapse the stack and accumulate the span until the top price is higher than the new price. return the total span

e.g. prices: 10, 6, 5, 4, 3, 7

after 3, the stack looks [(10,1), (6,1), (5,1), (4,1), (3, 1)],

when 7 arrives, [(10,1), (6,1), (5,1), (4,1), (3, 1), (7, 4 + 1)] = [(10, 1), (7, 5)]

Time complexity: O(1) amortized, each element will be pushed on to stack once, and pop at most once.

Space complexity: O(n), in the worst case, the prices is in descending order.




Related Problems

If you like my articles / videos, donations are welcome.

Buy anything from Amazon to support our website


One Comment

Leave a Reply