Minimum elemnt in constant time confusion

i have a doubt on the fact that u have given a formulae for implementing it using a stack. i have implemented it using two stack is it okay for find maximum at any point of time pushing and popping element into or from the stack.

source code:

#include<bits/stdc++.h>
using namespace std;

void pushh(int x,stack &a,stack &b)
{
if(a.empty()&& b.empty())
{
a.push(x);
b.push(x);

}

if(x>=b.top())
{
b.push(x);
}
else
{
int u=b.top();
b.push(u);
}
a.push(x);

}
void popp(stack&s1,stack&s2)
{
if(s1.empty()&&s2.empty())
{
cout<<“underflow”<<endl;
return;
}

s1.pop();
s2.pop();

}
void prntmax(stack &s2)
{
cout<<"the highest no. is "<<s2.top();
}
int main()
{
stacks1;
stacks2;
int n;
cin>>n;

while(n--)
{
    int y;
    cin>>y;
   pushh(y,s1,s2);


}
popp(s1,s2);
popp(s1,s2);

prntmax(s2);
return(0);
}

yes it is fine can find the max element at any point using 2 stack

1 Like

ohh it means we can use when space is not a constraint right?

yup space required is mandetory

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.