Saturday 23 July 2016

Get Maximum element of stack at any instance in O(1)

// Print the maximum value in the stack in O(1)

#include<stdio.h>
#include<stack>
#include <iostream>
#include<algorithm>
using namespace std;
#define ll long long int

int main() {

stack<ll> s;
ll n,t,q;
scanf("%lld", &n);
for (int i = 0; i < n; i++) {

 scanf("%lld", &q);
 //q=1 when push element in stack
 //q=2 when pop element from stack
 //q=3 when we have to print maximum element of current stack
if(q==1) // push element to stack (always push maximum element at top)

{
scanf("%lld", &t);
      if (s.empty()) {
           s.push(t);
      }
      else {
          s.push(max(t, s.top()));
      }
}

if(q==2) // pop element from stack
{
      if (!s.empty()) {
s.pop();
      }
}
if(q==3) //Prints maximum element of stack
{
printf("%lld\n", s.top());
}
}
return 0;
}

Basically here we always push the maximum element at top of stack as while pushing element in stack we check if the element to be pushed is greater than top element of stack we push that new element otherwise we push top of stack again thus always maintaining maximum element at the top.

No comments:

Post a Comment