• + 1 comment

    JAVA

    Approach Maintain a secondary maxStack which will keep track of the last max found.

    Code

    public static List<Integer> getMax(List<String> operations) {
            List<Integer> op = new ArrayList<>();
            Stack<Integer> mainStack = new Stack<>();
            Stack<Integer> maxStack = new Stack<>();
            for(String s : operations){
                if(s.startsWith("1")){
                    String[] ss = s.split(" ");
                    Integer x = Integer.valueOf(ss[1]);
                    //System.out.println(x);
                    mainStack.push(x);
                    if(maxStack.isEmpty() || x > maxStack.peek()){               
                        maxStack.push(x);            
                    }else{
                        maxStack.push(maxStack.peek());
                    }
                    System.out.println("X "+x+" Max "+maxStack.peek());   
                }else if(s.equals("2")){
                    mainStack.pop();
                    maxStack.pop(); 
                }else{
                    op.add(maxStack.peek());
                }
            }
        return op;
        }
    
    }