Run-time error in (Rainbow Array)

can anybody explain, Why this code is giving (Run-time Error(NZEC))

import java.util.Scanner;

class Code
{

    public static void main(String arg[])
    {
	int test,size,flag,flag2,i;
	Scanner in=new Scanner(System.in);
	test=in.nextInt();
	while(test!=0)
	{
		flag=0;
		flag2=0;
		size=in.nextInt();
		int arr[]=new int[size];
		for(i=0;i<size;i++)
			arr[i]=in.nextInt();
		for(i=1;i<size;i++)
		{
			if(arr[i-1]+1!=arr[i]&&arr[i-1]!=arr[i])
			{
				flag=arr[i-1];
				break;
			}
		}
		if(arr[size-1]==arr[0]&&arr[size-2]==arr[size-1])
			i=size;
		else if(arr[size-1]==flag&&arr[size-2]==arr[size-1])
			i=size;
		else
			i=1;
		for(;i<size;i++)
		{
			if(flag2%2==0)
			{
				if(arr[i-1]+1!=arr[i]&&arr[i-1]!=arr[i])
				{
					if(arr[i-1]==flag&&arr[i-2]!=flag)
					{
						flag2++;
					}
					else
					{	
						flag2=0;
						break;
					}
				}
			}
			else
			{
				if(arr[i-1]-1!=arr[i]&&arr[i-1]!=arr[i])
				{
					if(arr[i-1]==arr[0]&&arr[i-2]!=arr[0])
						flag2++;
					else
					{	
						flag2=0;
						break;
					}
				}
			}
		}
		if(flag2!=0)
			System.out.println("yes");
		else
			System.out.println("no");
		test--;
	}
	
}

}

You code is giving wrong answer for this test case…

1

14

1 2 3 4 5 6 7 7 6 5 4 3 2 1

For giving ArrayIndexOutOfBoundsException for this test case…

1

7

4 8 6 4 3 6 2

//