Source : https://www.hackerrank.com/challenges/maximum-element
You have an empty sequence, and you will be given 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, . The next lines each contain an above mentioned query. (It is guaranteed that each query is valid.)
Constraints
Output Format
For each type query, print the maximum element in the stack on a new line.
Sample Input
101 9721 2021 261 20231 913
Sample Output
2691
Source : https://www.hackerrank.com/challenges/maximum-element
Solution
// Karthikalapati.blogspot.com | |
import java.util.Scanner; | |
import java.util.Stack; | |
// All 3 queries (1:push, 2:delete, 3:print max) are all O(1) runtime | |
public class Solution { | |
public static void main(String[] args) { | |
Stack<Integer> stack = new Stack<Integer>(); | |
Stack<Integer> maxStack = new Stack<Integer>(); // keeps track of maximums | |
Scanner scan = new Scanner(System.in); | |
int N = scan.nextInt(); | |
for (int i = 0; i < N; i++) { | |
int query = scan.nextInt(); | |
switch (query) { | |
case 1: | |
int x = scan.nextInt(); | |
stack.push(x); | |
if (maxStack.isEmpty() || x >= maxStack.peek()) { | |
maxStack.push(x); | |
} | |
break; | |
case 2: | |
int poppedValue = stack.pop(); | |
if (poppedValue == maxStack.peek()) { | |
maxStack.pop(); | |
} | |
break; | |
case 3: | |
System.out.println(maxStack.peek()); | |
break; | |
default: | |
break; | |
} | |
} | |
scan.close(); | |
} | |
} |
No comments:
Post a Comment