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:
101 9721 2021 261 20231 913
Output:
2691
Approach
C++
#include <bits/stdc++.h>using namespace std;int main(){stack<int> maxstack, st;int n;cin >> n;for (int i = 0; i < n; i++){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);elsemaxstack.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