
Introduction
We all have come across the terms of e-trading, stocks, etc., right? Well, here this time we have kind of the same problem although don’t worry we won’t be dealing with trading algorithms or that sort. This stock span problem suggests that suppose we are given an array that contains n daily prices of a stock and we have to find out the span of the current stock’s price.
The Span of current stock is basically the number of days prior to the current day where the price of that sock was lesser or equal to the current stock. Well, for the basic approach we do not need any prerequisite but for the efficient approach of this solution, we require stacks.
Naive Approach
In this problem as we have seen earlier, we just have to find out how many such consecutive days are there prior to the current day where the price of the stock was lesser or equal. Let us see an example.

Taking one example of let Day 6 where the price is 75. For this day there are 3 more days where the price has been less – Day 5, 4, 3, and 6 itself. Hence the span of this stock at 6th day is 4.
The naïve approach will be to iterate over the day array for every day, and find out the nearest greatest index to the left where the price is greater than the current index.
Let this nearest greatest index to the left is called NGL. Let us see the code implementation:
#include <bits/stdc++.h>
using namespace std;
void stock_span(int *day,int n){
int *ans = new int[n];
memset(ans,0,n);
ans[0] = 1;
for(int i = 1;i<n;i++){
//i is the current day
int j = i-1; //starting from just left of current index
//to find the NGL index
while(j>=-1){
if(day[j] > day[i])
break;
j--;
}
//j will contain the NGL if j!=-1
if(j!=-1)ans[i] = (i - j);
// NGL - curr_idx will give the current span for the stock
else ans[i] = i+1;
}
for(int i= 0 ;i<n;i++)cout<<ans[i]<<" ";
}
int main() {
// your code goes here
int n;
cin>>n;
int *day = new int[n]; //day stock price
for(int i = 0;i<n;i++)cin>>day[i];
stock_span(day,n);
return 0;
}
- Time Complexity: Where n is the number of elements in the day array.
-
Space Complexity: Only for the extra answer array which can be easily eliminated.
Now let us revisit Stack as it will be necessary for our next approach i.e. the more efficient one.