Online Stock Span

Design a class that reads a stock's daily prices one at a time and reports each day's span. The span of today's price is the largest number of consecutive days, ending today and counting backward, on which the price was less than or equal to today's price. Implement `StockSpanner()`, which creates the object, and `int next(int price)`, which takes today's price and returns its span.

30:00

Online Stock Span
medium
Free written solution
Topics
Companies

Design a class that reads a stock's daily prices one at a time and reports each day's span. The span of today's price is the largest number of consecutive days, ending today and counting backward, on which the price was less than or equal to today's price. Implement StockSpanner(), which creates the object, and int next(int price), which takes today's price and returns its span.

Example 1:
Input: {"commands":["StockSpanner","next","next","next","next","next","next","next"],"values":[[],[100],[80],[60],[70],[60],[75],[85]]}
Output: [null,1,1,1,2,1,4,6]
Constraints:
  • 1≤price≤1051 \leq \text{price} \leq 10^5

  • At most 10410^4 calls will be made to next.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"commands":["StockSpanner","next","next","next","next","next","next","next"],"values":[[],[100],[80],[60],[70],[60],[75],[85]]}

prices by day

no prices yet

■ today■ inside today's span■ still on the stack

7 prices will arrive. The stack keeps (price, span) pairs whose prices strictly fall from bottom to top.

stack of (price, span), prices fall toward the top

size 0

empty

output []

0 days seen

Variables
VariableValue
stack[]
output[]
DepthFunction Call
Stack empty
0/33