Sunday, 29 January 2017

Maximum Elements

You have an empty sequence, and you will be given  queries. Each query is one of these three types:
1 x  -Push the element x into the stack.
2    -Delete the element present at the top of the stack.
3    -Print the maximum element in the stack.
Input Format
The first line of input contains an integer, . The next  lines each contain an above mentioned query. (It is guaranteed that each query is valid.)
Constraints 
 
 
Output Format
For each type  query, print the maximum element in the stack on a new line.
Sample Input
10
1 97
2
1 20
2
1 26
1 20
2
3
1 91
3
Sample Output
26
91
My Solution
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stack>
using namespace std;


int main() 
{
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
 stack<int> s;
 int n;
 scanf("%d",&n);
 for(int i=1;i<=n;i++)
 {
  int query;
  cin>>query;
  if(query == 1)
  {
   int x;
   cin>>x;
   if(s.empty()) 
     s.push(x);
   else 
   {
    s.push(max(x,s.top()));
   }
  }
  else if(query == 2)
  {
   s.pop();
  }
  else if(query == 3)
  {
   cout<<s.top()<<"\n";
  }
 }
 return 0;
}

Share:

0 comments:

Post a Comment