NZEC on AVERAGE

Why am I getting NZEC?
Problem: CodeChef: Practical coding for everyone

  public static void main (String[]args) throws java.lang.Exception
  {
    // your code goes here
    Scanner in = new Scanner (System.in);
    int n = in.nextInt ();
    int count=0;
    int[] a=new int[n];
    for (int i = 0; i < n; i++)
      {
        a[i]=in.nextInt();
      }
      Arrays.sort(a);
      
    for (int i = 0; i < n; i++)
      {
         int l=0;
         int r=1;
        while(l<=i && r<=n-i)
        {
            if ((a[i]-a[i-l])==(a[i+r]-a[i]))
            {
                count++;
                break;
            }
            else if (i==0 && r<n-i)
            {
                r++;
                continue;
            } 
            else if (i==n-1 && l<i)
            {
                l++;;
                continue;
            } 
            else if ((a[i]-a[i-l])<(a[i+r]-a[i]) && l<i)
            {
                l++;
                continue;
            }
            else if ((a[i]-a[i-l])<(a[i+r]-a[i]) && r<n-i)
            {
                r++;
                continue;
            }
            break;
        }
        
      }
      System.out.println(count);
  }

Consider the testcase:

5
48
5
35
20
22

I am getting NZEC on all testcases

Well, you’ve got a nice, reproducible testcase to debug with, then :slight_smile:

Have you tried debugging? With the testcase I gave you, if gives a huge hint as to what the problem is straight away:

>echo "5
48
5
35
20
22
" | ./run-java.sh 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
        at Codechef.main(manjot1151-AVERAGE.java:31)
1 Like