Java code: Why does this not work?

This is my first post on StackOverflow, I apologize if my post format is not standard, and please forgive me if my question is stupid.

I am making problems with hackerrank and the current goals of my problem are as follows:

You have an empty sequence and you will be given N requests. Each request is one of three types:

  • Push the x element onto the stack.
  • Delete the item present at the top of the stack.
  • Print the maximum item on the stack.

I already decided this, but I saw another solution in the discussions and thought about changing it. An alternative 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 was thinking about 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); } 

After that, it passes the default test case. But that fails 9/27 full test cases. Here is a small part of one of the test cases that fail. There are 100,000 requests, but I took 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 does he fail? Any help is appreciated.

EDIT:

If I enter the values ​​that I posted above with unmodified code, I get

 809288903 967650885 975612397 975612397 967650885 967650885 809288903 809288903 

With the modified code:

 809288903 967650885 975612397 975612397 975612397 975612397 975612397 975612397 
+5
source share

Source: https://habr.com/ru/post/1263307/


All Articles