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.
Approach
Maintain a secondary maxStack which will keep track of the last max found.
Code
publicstaticList<Integer>getMax(List<String>operations){List<Integer>op=newArrayList<>();Stack<Integer>mainStack=newStack<>();Stack<Integer>maxStack=newStack<>();for(Strings:operations){if(s.startsWith("1")){String[]ss=s.split(" ");Integerx=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());}elseif(s.equals("2")){mainStack.pop();maxStack.pop();}else{op.add(maxStack.peek());}}returnop;}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Maximum Element
You are viewing a single comment's thread. Return to all comments →
JAVA
Approach Maintain a secondary maxStack which will keep track of the last max found.
Code