[Opgelost] Maximum Element - Java Task (Stacks)

  

3
Onderwerp starter

You have an empty sequence, and you will be given N queries. Each query is one of these three types:

  • 1 x - Push the element x into the stack.
  • 2    - Delete the element present at the top of the stack.
  • 3    - Print the maximum element in the stack.

Input Format: The first line of input contains an integer, N. The next N lines each contain an above mentioned query. (It is guaranteed that each query is valid.)

Output Format: For each type 3 query, print the maximum element in the stack on a new line.

Constraints:
1 ≤ N ≤ 105 
1 ≤ x ≤ 109
1 ≤ type ≤ 3

Here is an examples:

maxim java
1 antwoord
2

Here is the answer my friend:

import java.util.Scanner;
import java.util.Stack;
 
public class Pr_03_MaximumElement {
    public static void main(String[] args) {
 
        Scanner sc = new Scanner(System.in);
        int commandCount = sc.nextInt();//GETTING THE FIRST NUMBER - HOW MANY NUMBERS WILL BE
 
        Stack<Integer> stack = new Stack<>();
        Stack<Integer> maxStack = new Stack<>();
        int max = Integer.MIN_VALUE;
 
        for (int i = 0; i < commandCount; i++) {
 
            int command = sc.nextInt();//THE COMMAND NUMBER - WHICH IS IN FRONT OF THE NUMBER
 
            if (command == 1) {
                int numToPush = sc.nextInt();//THE NUMBER AFTER THE COMMAND ONE
                stack.push(numToPush);
                if (max <= numToPush) {
                    max = numToPush;
                    maxStack.push(max);
                }
            } else if (command == 2) {
                int poppedItem = stack.pop();//IN THIS CASE WE ARE REMOVING THE ELEMENT PRESENT AT THE TOP OF THE STACK
                if (poppedItem == max) {
                    maxStack.pop();
                    if (maxStack.size() > 0) {
                        max = maxStack.peek();
                    } else {
                        max = Integer.MIN_VALUE;
                    }
                }
            } else {//FOR THE COMMAND WITH NUMBER 3 FOR PRINTING THE MAXIMUM ELEMENT IN THE STACK
                System.out.println(max);
            }
        }
    }
}
Deel: