Hey guys i have some data structure challenges that i really don't know how to solve better.
I had a correct solution but the time exceed some limit, the code should follow N instructions:
- add X number to a stack when I type 1
- delete the top of the stack with 2
- and print the max number in the stack with 3
It it suposed to be solved with arrays, arraylists, stack, queues or trees. That is what I did, but it exceed 6.51 s:
import java.util.*;
class Main {
public static void maxStack(int a, int val, Stack stack) {
switch (a) {
case 1:
stack.add(val);
break;
case 2:
if (stack.isEmpty()) {
break;
}
int c = (int) stack.pop();
break;
case 3:
Object o[] = stack.toArray();
Arrays.sort(o);
System.out.println(o[o.length - 1]);
break;
default:
break;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Stack<Integer> stack = new Stack<Integer>();
int val = 0;
int a = scan.nextInt();
while (a-- > 0) {
int t = scan.nextInt();
if (t == 1) {
val = scan.nextInt();
}
maxStack(t, val, stack);
}
scan.close();
}
}
Any recommendation?