Advertisement
at90

Maximum Element

May 21st, 2018
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.80 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.Stack;
  3.  
  4. public class MaximumElement {
  5.     public static void main(String[] args) {
  6.         Scanner sc = new Scanner(System.in);
  7.  
  8.         int commandsNum = sc.nextInt();
  9.         Stack<Integer> stack = new Stack<>(), maxStack = new Stack<>();
  10.         int maxNumber = 0;
  11.         for (int i = 0; i < commandsNum; i++) {
  12.             int command = sc.nextInt();
  13.             if (command == 1) {
  14.                 int value = sc.nextInt();
  15.                 if (maxNumber <= value) {
  16.                     maxNumber = value;
  17.                     maxStack.push(maxNumber);
  18.                 }
  19.                 stack.push(value);
  20.             } else if (command == 2) {
  21.                 if (stack.pop() == maxNumber) {
  22.                     maxStack.pop();
  23.                     if (maxStack.size() > 0) {
  24.                         maxNumber = maxStack.peek();
  25.                     } else {
  26.                         maxNumber = 0;
  27.                     }
  28.                 }
  29.             } else {
  30.                 System.out.println(maxNumber);
  31.             }
  32.         }
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement