Help needed! Where is my Java code wrong in BUILDB problem?

/* package codechef; // don’t place package name! */

import java.util.;
import java.lang.
;
import java.io.*;

/* Name of the class has to be “Main” only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner scn = new Scanner(System.in);
int T = scn.nextInt();

	while( T-- > 0 ){
	    int n = scn.nextInt();
	    int r = scn.nextInt();
	    int[] a = new int[n];
	    int[] b = new int[n];
	    for( int i = 0; i<n; i++ ){
	        a[i] = scn.nextInt();
	    }
	    int t = 0;
	    int tMax = 0;
	    for( int i = 0; i<n; i++ ){
	        t += scn.nextInt();
	        if( i != n-1 ){
	            t -= ( a[i+1] - a[i] ) * r;
	        }
	        if( t < 0 ){
	                t = 0;
	        }
	        if( t > tMax ){
	            tMax = t;
	        }
	    }
	    
	    System.out.println(tMax);
	}
}

}

I have seen editorial codes and they are using the same approach as me. Yet, my code wasn’t accepted during the contest, resulting into a WA. Can anyone point out what’s wrong?

You need to make 2 changes in your code.

  1. Converting tmax, t to long, because for some cases int may overflow
  2. check t>tMax after t += scn.nextInt();, if your question is why look at this test case
    3 10
    1 2 3
    100 2 3
    The actual answer is 100 but your code is giving 90

Solution → CodeChef: Practical coding for everyone

1 Like

I see. That makes sense.

Thanks a lot for pointing out these mistakes :slight_smile:

My pleasure. :slightly_smiling_face: