You are viewing a single comment's thread. Return to all comments →
For this particular question, we can simply keep a stack of the maximum values only at every level and ignore the original data of the stack.
Java O(1) solution :
public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int queries = in.nextInt(); Stack<Integer> maxValues = new Stack<Integer>(); while(queries-- > 0) { switch(in.nextInt()) { case 1 : int item = in.nextInt(); if (!maxValues.isEmpty()) { item = item > maxValues.peek() ? item : maxValues.peek(); } maxValues.push(item); break; case 2 : maxValues.pop(); break; case 3 : System.out.println(maxValues.peek()); break; } } in.close(); } }
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 →
For this particular question, we can simply keep a stack of the maximum values only at every level and ignore the original data of the stack.
Java O(1) solution :