Please help me know whats wrong with my solution

The problem name is “Maximum Length Even Subarray” . For the test cases my code is passing, but when submitting it if showing failed on a hidden test case. Please help me know what’s wrong in my code. and what can i do to fix it.

Below is my code:
import java.util.;
import java.lang.
;
import java.io.*;

class Codechef
{
public static void main (String args) throws java.lang.Exception
{
// your code goes here
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t–>0){int sum=0,cnt=0;int even=0;
int n=sc.nextInt();

for(int i=1;i<=n;i++){
    sum+=i;
    cnt++;
    if(sum%2==0){
        even=cnt;
    }
}
System.out.println(even);

    }
}

}

Hello there @infinic

I first debugged your code and handled one exception but it showed the below message.

When run on each test case individually, your code appears to be correct. However, when run on the entire test file, it returns a WA. The most common reasons for this are that you do not have a newline after each test case, or you do not reinitialize some variables in each test case.

Also here is the updated code -

// your code goes here
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        while (t-- > 0) {
            int sum = 0, cnt = 0;
            int even = 1;
            int n = sc.nextInt();

            for (int i = 1; i <= n; i++) {
                sum += i;
                cnt++;
                if (n == 1) {
                    System.out.println("0");
                    break;
                }
                if (sum % 2 == 0) {
                    even = cnt;
                }
            }
            System.out.println(even);
        }

So to deal with it, you can try another method to solve this question.

Here is my approach in JAVA

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

class Codechef
{
    public static void main(String[] args) throws java.lang.Exception
    {
        // your code goes here
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        for (int i = 0; i < t; i++) {
            int n = sc.nextInt();
            if (((n * (n + 1)) / 2) % 2 == 0) {
                System.out.println(n);
            } else {
                System.out.println(n - 1);
            }
        }
    }
}

Hope it helps :blush: