The stock span problem is a financial problem where we have a series of n daily price quotes for a stock and we need to calculate the span of the stock’s price for all n days.
The spanS[i] of the stock’s price on a given day i is defined as the maximum number of consecutive days (starting from today and going backward) for which the stock price was less than or equal to its price on day i.
Input: prices =[100,80,60,70,60,75,85]Output: [1,1,1,2,1,4,6]Explanation: For each day, the span is calculated as follows:Price Span Reason
1001(No previous day)801(No previous day <=80)601(No previous day <=60)702(Day 2 and 3 itself)601(No previous day <=60)754(Days 3,2,1, and 0)856(Days 5,4,3,2,1, and 0)
Example 2:
1
2
3
4
5
6
7
8
9
Input: prices =[10,4,5,90,120,80]Output: [1,1,2,4,5,1]Explanation: For each day, the span is calculated as follows:- Day 0: Price =10, Span =1- Day 1: Price =4, Span =1- Day 2: Price =5, Span =2- Day 3: Price =90, Span =4- Day 4: Price =120, Span =5- Day 5: Price =80, Span =1
classSolution {
publicint[]calculateSpan(int[] prices) {
int n = prices.length;
int[] span =newint[n];
for (int i = 0; i < n; i++) {
span[i]= 1;
for (int j = i - 1; j >= 0; j--) {
if (prices[j]<= prices[i]) {
span[i]++;
} else {
break;
}
}
}
return span;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defcalculateSpan(self, prices: List[int]) -> List[int]:
n = len(prices)
span = [0] * n
for i in range(n):
span[i] =1for j in range(i -1, -1, -1):
if prices[j] <= prices[i]:
span[i] +=1else:
breakreturn span
To solve the stock span problem efficiently, we can use a monotonic decreasing stack to store the indices of the days. For each day i, we pop elements from the stack until we find a day with a price greater than the price of the current day. The span for the current day will then be the difference in indices. So,
1
span[i]= i - ngl(i)if ngl(i) exists otherwise -1
where NGL is nearest greater element on the left of current element. if it exists.
Here is the approach:
Initialize a stack to keep the indices of the days.
Initialize an array to store the span values.
Iterate through the price list:
For each price, pop elements from the stack until the top of the stack has a price greater than the current price.
If the stack is empty, it means all previous prices are less than the current price’s price.