javaarraysalgorithmsub-arraykadanes-algorithm

Max subArray => IllegalArgumentException: 6 > 5


The method is working as intended, but while I was trying multiple cases, I got this weird issue, so hopefully someone can understand why and explain it to me, since 6 > 5 looks logically sound to me, and when I try to invert a negative number to a positive, it works fine again 😕

{2, -5, 6, -1, 4, -10, 2, 3, -2, 5, -1, 2, -4, 3,1} // the array that causes   the issue
public int[] maxSubArray(int[] arr){
   int currentMax = arr[0];
   int currentIndex = 0;
   int max = arr[0];
   int startIndex = 0;

   for(int i = 1; i < arr.length; i++){
       if(arr[i] > currentMax + arr[i]){
           startIndex = i;
       }
       currentMax = Math.max(currentMax + arr[i], arr[i]);
       if (currentMax > max){
           currentIndex = i;
       }
       max = Math.max(currentMax, max);

   }
   return Arrays.copyOfRange(arr, startIndex, currentIndex + 1);
}    

Solution

  • The exception results from calling Arrays.copyOfRange with a from index that is greater than the to index. You are only keeping track of the start index of the current subarray under consideration (the startIndex variable) and the end index of the subarray with maximum sum (the currentIndex variable), but have neglected to track the start index of the subarray with maximum sum.

    Your current code can be fixed with just a few changes.

    First, add a variable to store the start index of the subarray with the maximum sum found so far.

    int maxSubarrayStart = 0;
    

    Update this variable when a larger subarray sum is found.

    if (currentMax > max){
        maxSubarrayStart = startIndex; // add this line
        currentIndex = i;
    }
    

    Finally, use that index to construct the return value.

    return Arrays.copyOfRange(arr, maxSubarrayStart, currentIndex + 1);