0
#include<bits/stdc++.h>
int* stockSpan(int *price, int size)  {
    // Write your code here
    int *output=new int[size];
    stack<int>input;
    stack<int>auxiliary;
    for(int i=0;i<size;i++){
        if(input.size()==0){
            input.push(price[i]);
            output[i]=1;
        }
        else{
            if(input.top()<price[i]){
               while(input.top()<price[i] && !input.empty()){
                   auxiliary.push(input.top());
                   input.pop();
               }
                output[i]=auxiliary.size()+1;
                while(!auxiliary.empty()){
                    input.push(auxiliary.top());
                    auxiliary.pop();
                }
                input.push(price[i]);
            }
            else{
                input.push(price[i]);
                output[i]=1;
            }
        }  
    }
    return output;
}

This is my approach to solve the stock span problem with two stacks but I am getting a runtime error. Please point out the mistake.

  • 1
    What is the runtime error you get? What is the output you expect? Please provide a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). Also: what is the stock span problem? Please provide a link or a short explanation. – francesco Jul 10 '21 at 07:05
  • 2
    Also, [do not include bits/stdc++.h](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – francesco Jul 10 '21 at 07:06

1 Answers1

0

Try swapping this input.top()<price[i] && !input.empty() to this !input.empty() && input.top()<price[i] : you need to check if the stack is not empty before taking its top.

Also, you didn't add using namespace std;. It's needed when you use stack.

Mohamed Akram
  • 416
  • 4
  • 12