share my java solution!


  • 0
    T
    class MaxStack {
        Stack<Integer> st = new Stack<>();
        Stack<Integer> st_max = new Stack<>();
        int max = Integer.MIN_VALUE;
        /** initialize your data structure here. */
        public MaxStack() {
            st_max.add(Integer.MIN_VALUE);
        }
        
        public void push(int x) {
            if(x>=max){
                st_max.add(x);
                max = x;
            }
            st.add(x);
        }
        
        public int pop() {
            int val = st.pop();
            if(val==max){
                st_max.pop();
            }
            max = st_max.peek();
            return val;
        }
        
        public int top() {
            return st.peek();
        }
        
        public int peekMax() {
            return max;
        }
        
        public int popMax() {
            int retrieve_max = st_max.peek();
            
            Stack<Integer> temp_st = new Stack<>();
            while(!st.isEmpty() && st.peek()!=max){
                temp_st.add(st.pop());
            }
            st.pop();
            st_max.pop();
            max = st_max.peek();
            while(temp_st.size()!=0){
                push(temp_st.pop());
            }
            return retrieve_max;
        }
    }
    
    /**
     * Your MaxStack object will be instantiated and called as such:
     * MaxStack obj = new MaxStack();
     * obj.push(x);
     * int param_2 = obj.pop();
     * int param_3 = obj.top();
     * int param_4 = obj.peekMax();
     * int param_5 = obj.popMax();
     */
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.