HackerRank 'Maximum Element' Solution

by Srikant Padala on May 21, 2018, 8:15 pm


Explanation


  • Maintain the current max element along with the actual element in the stack.
  • Whenever we push/pop an element, change the current maximum.

Maximum Element Problem Statement

Video

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

typedef long long ll;
int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    ll nq, qtype, x, cmax = INT_MIN;
    stack<pair<ll,ll>> stk;
    cin >> nq;
    while(nq--) {
        cin >> qtype;
        if(qtype == 1) {
            cin >> x;
            cmax = max(x, cmax);
            stk.push(make_pair(x, cmax));
        } else if(qtype == 2) {
            stk.pop();
            if(stk.empty())
                cmax = INT_MIN;
            else
                cmax = stk.top().second;
        } else {
            cout << cmax << endl;
        }
    }
    return 0;
}

Coming Soon.