HackerRankJun 15, 2025

Maximum Element

Hazrat Ali

HackerRank

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.

Function Description

Complete the getMax function in the editor below.

getMax has the following parameters:
string operations[n]: operations as strings

Returns
int[]: the answers to each type 3 query

Input Format

The first line of input contains an integer, . The next  lines each contain an above mentioned query.

All queries are valid.

Sample Input

STDIN   Function
-----   --------
10      operations[] size n = 10
1 97    operations = ['1 97', '2', '1 20', ....]
2
1 20
2
1 26
1 20
2
3
1 91
3

Sample Output

26
91

Solution

#include <iostream>
#include <stack>
#include <sstream>
#include <string>
using namespace std;

 

int main() {

 

    int n, query_type, query_value, maximum;
    string query_line;
    stack<int> s, max_tracker;
    cin >> n;
    cin.ignore();
    for (int i = 0; i < n; i++) {
        getline(cin, query_line);
        istringstream ss(query_line);
        ss >> query_type >> query_value;
        switch (query_type) {
        case 1:
            s.push(query_value);
            if (max_tracker.empty() || max_tracker.top() <= query_value)
                max_tracker.push(query_value);
            break;
        case 2:
            if (s.top() == max_tracker.top())
                max_tracker.pop();
            s.pop();
            break;
        default:
            cout << max_tracker.top() << endl;
        }
    }
    return 0;
}













Comments