Maximum Element

You have an empty sequence, and you will be given N 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.

Example:

Input:

10
1 97
2
1 20
2
1 26
1 20
2
3
1 91
3

Output:

26
91

Approach

C++

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

int main()
{
    stack<intmaxstackst;
    int n;
    cin >> n;
    for (int i = 0i < ni++)
    {
        int x;
        cin >> x;
        if (x == 1)
        {
            int y;
            cin >> y;
            if (maxstack.empty())
                maxstack.push(y);
            else
            {
                if (maxstack.top() < y)
                    maxstack.push(y);
                else
                    maxstack.push(maxstack.top());
            }
            st.push(y);
        }
        if (x == 2)
        {
            if (!maxstack.empty())
                maxstack.pop();
            st.pop();
        }
        if (x == 3)
            cout << maxstack.top() << "\n";
    }
    return 0;
}


No comments:

Post a Comment