Online Stock Span

Design a data structure that receives daily stock prices and returns the stock span for the current day. The span of the stock’s price on a given day is the maximum number of consecutive days (starting from today and going backward) for which the price was less than or equal to today’s price. Example: Input: prices = [100,80,60,70,60,75,85] Output: [1,1,1,2,1,4,6] Explanation: On day 6 with price 85, the span is 6 because the last 6 days had prices <= 85. Pattern focus: Monotonic Increasing Stack for Span.

Input Format

prices = daily stock prices

Output Format

span for each day in order

Constraints

  • 1 <= prices.length <= 10^5
  • 1 <= prices[i] <= 10^5

Examples

Example 1:

Input:

prices = [100,80,60,70,60,75,85]

Output:

[1,1,1,2,1,4,6]

Explanation:

Store price and span pairs so each day is processed once.

Example 2:

Input:

prices = [31,41,48,59,79]

Output:

[1,2,3,4,5]

Explanation:

Every new price is higher than all previous prices, so spans grow monotonically.

Loading...
Online Stock Span - Monotonic Stack Queue