Chapter 7 · Simulation

Stock Span Simulator

← Chapter 7
Ready.
Monotonic stack
Top

Stock Span Simulator

The span of day i is the number of consecutive days, ending with day i and counting backward, whose price is less than or equal to the price on day i.

How to use it

  • Type 1–10 positive Prices separated by commas and press Load, or use Sample / Random.
  • Next / Back move one step forward or back, Play runs through every step, Reset returns to the start, and Cancel stops playback.

The monotonic stack algorithm

  1. For each day i, pop indices while the price at the top of the stack is ≤ price[i].
  2. If the stack is empty, span[i] = i + 1; otherwise span[i] = i − top.
  3. Push i.

The stack holds days with strictly decreasing prices. Each index is pushed once and popped at most once, so the whole run takes O(n) time, against O(n²) for the naive method.