Page 1 of 1

Max subarray => illegalArgumentException: 6> 5

Posted: 24 Aug 2025, 01:10
by Anonymous
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);
}