You are viewing a single comment's thread. Return to all comments →
Here's my version of solution for this problem.
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); Stack<Integer> stack = new Stack<Integer>(); Stack<Integer> maxStack = new Stack<Integer>(); while (n > 0) { int choice = sc.nextInt(); if (choice == 1) { Integer val = sc.nextInt(); if (val >= getStackMax(maxStack)) maxStack.push(val); stack.push(val); } else if (choice == 2) { Integer value = stack.pop(); if (value == getStackMax(maxStack)) maxStack.pop(); } else if (choice == 3) { if (!maxStack.isEmpty()) { System.out.println(getStackMax(maxStack)); } } n--; } sc.close(); } private static Integer getStackMax(Stack<Integer> s) { if (s.isEmpty()) return Integer.MIN_VALUE; return s.peek(); } }
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 →
Here's my version of solution for this problem.