this is my first time posting on StackOverflow, I apologize if my post format isn't standard and please forgive me if my question is stupid.
I'm doing challenges on hackerrank and the current objectives of my problem are as follows:
You have an empty sequence, and you will be given N queries. Each query is one of these three types:
- Push the element x onto the stack.
- Delete the element present at the top of the stack.
- Print the maximum element in the stack.
I've already solved it, but I saw another solution in the discussions and thought of modifying it. The alternate solution was:
public class Solution {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int n = inp.nextInt();
Stack<Integer> S = new Stack<>();
Stack<Integer> largest_stack = new Stack<>();
largest_stack.push(0);
for(int i=1; i<=n;i++) {
int query = inp.nextInt();
if(query==1){
int newtop=inp.nextInt();
S.push(newtop);
if(S.peek()>=largest_stack.peek()){
largest_stack.push(S.peek());
}
}
if(query==2) {
if(S.peek()==largest_stack.peek()){
largest_stack.pop();
}
S.pop();
}
if(query==3){
System.out.println(largest_stack.peek());
}
}
}
}
I thought of replacing S.peek() with newtop in this part
if(S.peek()>=largest_stack.peek()){
largest_stack.push(S.peek());
}
So I get
if(S.peek()>=largest_stack.peek()){
largest_stack.push(newtop);
}
Upon doing so, it's passes the default test case. But it fails 9/27 total test cases. Here is a small portion of one of the test cases which is failing. There are 100000 queries but I've taken only the first 21.
21
1 809288903
3
1 55967040
1 967650885
1 21752006
3
2
1 61250743
1 975612397
3
3
2
3
2
3
2
2
3
3
2
1 784642399
Why is it failing? Any help would be much appreciated.
EDIT:
If I input the values I've posted above with the non modified code, I get
809288903
967650885
975612397
975612397
967650885
967650885
809288903
809288903
With modified code:
809288903
967650885
975612397
975612397
975612397
975612397
975612397
975612397