The Hidden Problem
This is secretly just the Previous Greater Element problem! The span breaks on the exact day that a previous price was strictly greater than today's price.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
The span of the stock's price today is the maximum number of consecutive days (starting from today and going backward) for which the stock price was less than or equal to today's price.
This is secretly just the Previous Greater Element problem! The span breaks on the exact day that a previous price was strictly greater than today's price.
Instead of storing the actual stock prices in the stack, we MUST store their indices. To calculate the span, we just do `currentIndex - previousGreaterIndex`.
If the stack becomes empty, it means today's price is higher than ALL previous prices. Thus, the span is simply `currentIndex + 1`.