Please help me correct my code it is showing index out of bounds error

import java.util.*;
public class Main {
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) {
int t = sc.nextInt();
while(t!=0){
maxLength();
t–;
}

}
public static void maxLength(){
	int n = sc.nextInt();
	int[] a = new int[n];
	int max =0;
	int i = 0;
	while(i<n){
		a[i]=sc.nextInt();
		if(a[i]>max){
			max=a[i];}
		i++;
	}
	int count=0;
	int flag=0;
	for(int j =1;j<=n;j++){
		if(a[j-1]<a[j]){
			count+=1;
			if(a[j]==max && flag==0){
				count+=1;
				flag=1;
				j++;
				if(a[j]<max){
					count+=1;
					j++;
					if(a[j]<a[j-1]&&j<n){
					while(a[j]<a[j-1]&&j<n){
						count+=1;
						j++;
						
					}}
					else{

						break;
					}
				}else{
					count=0;
				}
			}else{
				count=0;
			}
			

		}
	}

	
System.out.println(count);	
		

}

}

Try this Approach

We create two arrays - β€˜inc’ and β€˜dec’

  1. inc[i] stores the length of increasing subarray till i.
  2. dec[i] stores the length of decreasing subarray starting from index i.
  3. Doing so gives us the length of increasing and decreasing subarray at each index in O(n) time.
  4. We calculate the length of the longest bitonic subarray by finding the maximum inc[i] + dec[i] - 1
  5. We subtract one since the current element at ith index is included in both the increasing and decreasing subarray lengths.

Algorithm

  1. Initialize inc[0] to 1 and dec[n-1] to 1
  2. Creating inc[] array
    a. Till end of the array ie, i=1 to n, if arr[i] > arr[i-1] then inc[i] = inc[i-1] + 1. else, inc[i] = 1
  3. Creating dec[] array
    a. From the end of the array ie, i = n-2 till i =0, if arr[i] > arr[i+1] then dec[i] = dec[i+1] +1 else, dec[i] = 1