Max subarray => illegalArgumentException: 6> 5

Post a reply

Smilies
:) :( :oops: :chelo: :roll: :wink: :muza: :sorry: :angel: :read: *x) :clever:
View more smilies

BBCode is ON
[img] is ON
[flash] is OFF
[url] is ON
Smilies are ON

Topic review
   

Expand view Topic review: Max subarray => illegalArgumentException: 6> 5

by Anonymous » 24 Aug 2025, 01:10

Die Methode funktioniert wie beabsichtigt, aber während ich mehrere Fälle ausprobiert habe, habe ich dieses seltsame Problem bekommen, also kann ich hoffentlich jemand verstehen, warum und erklären es mir, da 6> 5 für mich logisch klingen und wenn ich versuche, eine negative Zahl in ein positives zu umwenden, funktioniert es wieder gut 😕 < /p>

Code: Select all

    {2, -5, 6, -1, 4, -10, 2, 3, -2, 5, -1, 2, -4, 3,1} // the array that causes   the issue
< /code>
    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);
}

Top