-1
enter code herepublic class maximum_subarray_bruteforce {
public static void main(String[] args) {
    int arr[]= {-2,1,-3,4,-1,2,1,-5,4};
    System.out.println(sar(arr));

}
static int sar( int arr[]){
    int sum =0;
    int max=-1;
    for (int i=0;i<arr.length;i++){
        for(int j=i+1;j< arr.length;i++){
            for(int k=i+2;k<arr.length;k++ ){
                sum=arr[i]+arr[j]+arr[k];
                if(sum>max){
                    max=sum;
                }
                if(sum<max){
                    sum=0;
                }
            }
        }

    }
    return max;

everytinme i execute this code it gives me array out of bounds error. i am running three loops and my compiler is showing the error somewhere in the second loop the j one, i am using arr.length because the name of my array is arr. i have done this problem with o(n) complexity but am trying to do this with o(n^3) and o(n^2) too. please assist

}

}

1 Answers1

0

When i is at the last index, in your case [8], When you are running the second loop, i +1 would be at index [9], which is out of bounds for the given array length.

Zaid Fanek
  • 23
  • 5