3 of my test cases are showing TLE erroe how can I resolve it

import java.util.;
import java.lang.
;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] a = new int[N];
int i = 0;
while(i<N){
a[i]=sc.nextInt();
i++;
}
System.out.println(findMax(a,N));

}
public static int findMax(int[] a,int n){
	int result=0;
	for(int i =1;i<n-1;i++){
		int left=a[i];
		for(int j=0;j<i;j++){
			left=Math.max(left,a[j]);
		}
		int right=a[i];
		for(int k=i+1;k<n;k++){
			right=Math.max(right,a[k]);
		}
		result+=Math.min(left,right)-a[i];
	}
	return result;
}

}

Loop from index 0 to the end of the given array. If a wall greater than or equal to the previous wall is encountered then make note of the index of that wall in a var called prev index. Keep adding previous wall’s height minus the current (ith) wall to the variable water. Have a temporary variable that stores the same value as water. If no wall greater than or equal to the previous wall is found then quit. If prev index < size of the input array then subtract the temp variable from water, and loop from end of the input array to prev_index and find a wall greater than or equal to the previous wall (in this case, the last wall from backwards).
see this for reference: