AlgoMaster Logo

Online Stock Span

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The brute force approach involves keeping track of all the stock prices encountered so far and then, for each new price, iterating backwards through the stored prices to calculate the span directly. This means, for each price, we need to traverse backwards until a price higher than the current price is found.

Steps:

  1. Initialize a list to store the stock prices.
  2. For each new price, traverse backwards in the list:
    • Increase the span as long as prices are less than or equal to the current price.
  3. Return the span once a higher price is found or the list is exhausted.

Code:

2. Using Stack

Intuition:

To optimize the previous approach, we can utilize a stack to maintain a history of price indices that help in quickly determining the span. We store prices along with their respective spans in a stack. Each time a price is added, all prices less than or equal to the current price are popped from the stack, effectively calculating the span in constant amortized time.

Steps:

  1. Use a stack to store pairs of prices and their spans.
  2. For each incoming price:
    • Pop elements from the stack while they are less than or equal to the current price and accumulate their spans.
    • The span for the current price is the accumulated span plus one (for the current price itself).
  3. Push the current price and its calculated span onto the stack.

Code: