Stock Span Problem
Monotonic Stack & Queue Problems DSA practice problem on Onlearn.
Difficulty: medium.
Topics: Stock Span Problem, Arrays, Stack, Monotonic Stack, Time Complexity, Space Complexity, Brute Force, Optimization, array traversal, complexity analysis, monotonic stack, stack, Next/Previous Greater/Smaller Element.
Stock Span Problem Problem Statement The stock span problem is a financial problem where we have a series of n daily stock prices and we need to calculate the span of the stock's price for the current day. The span S i of the stock price on a given day i is defined as the maximum number of consecutive days (starting from day i and going backward) for which the stock price was less than or equal to the price on day i. Formally, S i is the count of days j (where j <= i) such that for all k from j to i, prices[k] <= prices[i]. If no such day j exists (i.e., prices[i] is the lowest price so far), then the span is i + 1. Input Specification The first line contains an integer N, representing the number of days. The second line contains N space separated integers, prices[0], prices[1], ..., prices[N 1], representing the daily stock prices. Output Specification Print N space separated integers, where the i th integer is the span for prices[i]. Constraints 1 <= N <= 10^5 1 <= prices[i] <= 10^9 Sample Test Cases Sample Input 1 Sample Output 1 Explanation for Sample 1: For 100: Span is 1 (100 itself). For 80: Span is 1 (80 itself, as 100 80). For 60: Span is 1 (60 itself, as 80 60). For 70: Span is 2 (70, 60. As 80 70, we stop at 80). For 60: Span is 1 (60 itself, as 70 60). For 75: Span is 4 (75, 60, 70, 60. As 80 75, we stop at 80). For 85: Span is 6 (85, 75, 60, 70, 60, 80. As 100 85, we stop at 100).