Stock span problem | Practice | GeeksforGeeks

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 stocks price for all n days. 
The span Si of the stocks price on a given day i is defined as the maximum number of consecutive days just before the given day, for which the price of the stock on the current day is less than or equal to its price on the given day.
For example, if an array of 7 days prices is given as {100, 80, 60, 70, 60, 75, 85}, then the span values for corresponding 7 days are {1, 1, 1, 2, 1, 4, 6}.
Example 1:
Input: 
N = 7, price[] = [100 80 60 70 60 75 85]
Output:
1 1 1 2 1 4 6
Explanation:
Traversing the given input span for 100 
will be 1, 80 is smaller than 100 so the 
span is 1, 60 is smaller than 80 so the 
span is 1, 70 is greater than 60 so the 
span is 2 and so on. Hence the output will 
be 1 1 1 2 1 4 6.

Example 2:
Input: 
N = 6, price[] = [10 4 5 90 120 80]
Output:
1 1 2 4 5 1
Explanation:
Traversing the given input span for 10 
will be 1, 4 is smaller than 10 so the 
span will be 1, 5 is greater than 4 so 
the span will be 2 and so on. Hence, the 
output will be 1 1 2 4 5 1.
User Task:
The task is to complete the function calculateSpan() which takes two parameters, an array price[] denoting the price of stocks, and an integer N denoting the size of the array and number of days. This function finds the span of stock's price for all N days and returns an array of length N denoting the span for the i-th day.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ N ≤ 105
1 ≤ C[i] ≤ 105
0
20bd5a052019 hours ago
class Node
{
   int ele;
   int idx;
   Node(int ele,int idx)
   {
       this.ele=ele;
       this.idx=idx;
   }
}
class Solution
{
   //Function to calculate the span of stockâ€TMs price for all n days.
   public static int[] calculateSpan(int stocks[], int n)
   {
       // Your code here
       Stack<Node> st=new Stack<>();
	    int span[]=new int[stocks.length];
	    span[0]=1;
	    st.push(new Node(stocks[0],1));
	    for(int i=1;i<span.length;i++)
	    {
	        if(st.peek().ele>stocks[i])
	        {
	            span[i]=1;
	            st.push(new Node(stocks[i],span[i]));
	        }
	        else 
	        {
	            while(!st.isEmpty()&&st.peek().ele<=stocks[i])
	            {
	                span[i]+=st.pop().idx;
	            }
	            span[i]+=1;
	            st.push(new Node(stocks[i],span[i]));
	        }
	    }
	    return span;
       
       
   }
   
}
0
gfgraj2 days ago
  vector <int> calculateSpan(int a[], int n)   {      vector<int>v;      v.push_back(1);      stack<int>s;      stack<int>ind;      ind.push(0);      s.push(a[0]);      for(int i=1;i<n;i++){          int flag=1;                    if(a[i]<s.top()){              v.push_back(flag);              s.push(a[i]);              ind.push(i);              continue;          }          while(!s.empty() && a[i]>=s.top()){              s.pop();                            flag+=v[ind.top()];              ind.pop();          }          s.push(a[i]);          ind.push(i);          v.push_back(flag);                                    }      return v;         }
0
hharshit81182 weeks ago
class Solution{   public:   //Function to calculate the span of stockâ€TMs price for all n days.   vector <int> calculateSpan(int price[], int n)   {      // Your code here      stack<int> s;      s.push(0);      vector<int> v;      v.push_back(1);      int i =1;      while(i<n){          while(s.empty()==false && price[s.top()] <= price[i]){              s.pop();          }          if(s.empty()==true)          v.push_back(i+1);          else          v.push_back(i-s.top());          s.push(i);          i++;      }      return v;   }};
0
mamoonakhterrock20022 weeks ago
 public static int[] calculateSpan(int price[], int n)   {          int S[] = new int[n];       Stack<Integer> st = new Stack<>();       st.push(0);       // Span value of first element is always 1       S[0] = 1;       // Calculate span values for rest of the elements       for (int i = 1; i < n; i++) {           // Pop elements from stack while stack is not           // empty and top of stack is smaller than           // price[i]           while (!st.empty() && price[st.peek()] <= price[i])               st.pop();           // If stack becomes empty, then price[i] is           // greater than all elements on left of it, i.e.,           // price[0], price[1], ..price[i-1]. Else price[i]           // is greater than elements after top of stack           S[i] = (st.empty()) ? (i + 1) : (i - st.peek());           // Push this element to stack           st.push(i);       }               return S;        }
0
pkb9825112 weeks ago
 stack<pair<int,int>>s;      vector<int>ans;      for(int i=0;i<n;i++){          int days=1;          while(!s.empty() && s.top().first<=price[i] ){             days+=s.top().second;             s.pop();          }          s.push({price[i],days});          ans.push_back(days);      }      return ans;
+1
archit232002 weeks ago
JAVA Solution Based on Aditya Verma's approach:-
 
[IMP]:-If your original solution is not passing the test cases,it is most probably because you took “< “ instead of ”< =” in the conditions which is very important for the correct result.
 
class Solution
{
    //Function to calculate the span of stockâ€TMs price for all n days.
    static class ValueNIndex{
        int value;
        int index;
        ValueNIndex(){}
        ValueNIndex(int value,int index){
            this.value=value;
            this.index=index;
        }
        int getValue(){
            return this.value;
        }
        int getIndex(){
            return this.index;
        }
        void setValInd(int value,int index){
            this.value=value;
            this.index=index;
        }
    }
    public static int[] calculateSpan(int arr[], int n)
    {
        if(arr.length==0){
            int ans[]={};
            return ans;
        }
        if(arr.length==1){
            int ans[]={1};
            return ans;
        }
        Stack<ValueNIndex> st=new Stack<>();
        ArrayList<Integer> ans =new ArrayList<>();
        for(int i=0;i<arr.length;i++){
            if(st.isEmpty()==false && st.peek().value<=arr[i]){
                while(st.isEmpty()==false && st.peek().value<=arr[i]){
                    st.pop();
                }
            }
            if(st.isEmpty()==false && st.peek().value>arr[i]){
                ans.add(i-st.peek().index);
            }
            if(st.isEmpty()==true){
                ans.add(i+1);
            }
            ValueNIndex el=new ValueNIndex(arr[i],i);
            st.push(el);
        }
        int result[]=new int[ans.size()];
        for(int i=0;i<ans.size();i++){
            result[i]=ans.get(i);
        }
        return result;
    }
    
}
+1
aloksinghbais022 weeks ago
C++ solution having time complexity as O(N) and space complexity as O(N) is as follows :- 
 
Execution Time :- 1.04 / 2.32 sec
 
vector <int> calculateSpan(int price[], int n){       stack<int> stk;       vector<int> ngel(n);       for(int i = 0; i < n; i++){           while(!stk.empty() && price[stk.top()] <= price[i]){               stk.pop();           }           if(stk.empty()) ngel[i] = -1;           else ngel[i] = stk.top();           stk.push(i);       }              vector<int> ans(n);       ans[0] = 1;       for(int i = 1; i < n; i++){           if(ngel[i] == -1) ans[i] = i+1;           else{               ans[i] = i - ngel[i];           }       }              return (ans);   }
0
adityagagtiwari3 weeks ago
Simple solution using stacks and a pair for keeping the state!
class Pair
{
   int value;
   int span;
   Pair(int value,int span)
   {
       this.value = value;
       this.span = span;
   }
}
class Solution
{
   //Function to calculate the span of stockâ€TMs price for all n days.
   public static int[] calculateSpan(int arr[], int n)
   {
       // Your code here
       Stack<Pair> stack = new Stack<>();
       int[] span =new int[n];
       stack.push(new Pair(arr[0],1));
       span[0] = 1;
       for(int i=1;i<n;i++)
       {
           if(stack.peek().value>arr[i])
           {
               span[i] = 1;
               stack.push(new Pair(arr[i],span[i]));
           }
           else 
           {
               while(stack.size()>0 && arr[i]>=stack.peek().value)
               {
                   Pair removed = stack.pop();
                   span[i]+=removed.span;
               }
               //for including itlself in the span
               span[i]+=1;
               stack.push(new Pair(arr[i],span[i]));                
           }
       }
       return span;
   }
   
}
0
aakashsoni24863 weeks ago
vector <int> calculateSpan(int price[], int n)   {      // Your code here      vector<int>ans(n);      stack<int>st;      ans[0]=1;      st.push(0);      for(int i=1;i<n;i++){          while(!st.empty()&&price[st.top()]<=price[i]){              st.pop();          }          if(st.empty()){              ans[i]=i+1;          }          else{              ans[i]=i-st.top();          }          st.push(i);      }      return ans;         }
0
himanshukug19cs3 weeks ago
java solution
 
       int[] ans = new int[n];Stack<Integer> st = new Stack<>();st.push(0);ans[0]=1;for(int i=1;i<n;i++){   while(!st.empty()&&price[i]>=price[st.peek()]){       st.pop();   }   if(st.empty())       ans[i]=i+1;   else{       ans[i]=i-st.peek();   }       st.push(i);}return ans;
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.