We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • HackerRank Home

    HackerRank

  • |
  • Prepare
  • Certify
  • Compete
  • Apply
  • Hiring developers?
  1. Prepare
  2. Data Structures
  3. Stacks
  4. Maximum Element
  5. Discussions

Maximum Element

Problem
Submissions
Leaderboard
Discussions
Editorial

    You are viewing a single comment's thread. Return to all comments →

  • j_umbo
    4 months ago+ 0 comments

    A very easy solution in c++

    #include <bits/stdc++.h>
    
    using namespace std;
    
    int main(){
        int n;
        cin>>n;
        stack<int> s;
        stack<int> maxStack;
        while(n--){
            int a,b;
            cin>>a;
            if(a==1){
                cin>>b;
            }
            if(a==1){
                s.push(b);
                if(maxStack.empty()){
                    maxStack.push(b);
                }
                else{
                    maxStack.push(max(maxStack.top(),b));
                }
            }
            else if(a==2){
                s.pop();
                maxStack.pop();
            }
            else{
                cout<<maxStack.top()<<endl;
            }
        }
    }
    
    -6|
    Permalink
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy