简体   繁体   中英

Sub-Array Max Sum

I'm looking over an assignment that I finished a few days ago and realized I'm not supposed to use constants. The assignment is the well-known "find the largest sum of a sub-array of integers both positive and negative recursively using a divide and conquer approach" problem. My algorithm works, but a part of it uses a constant in order to figure out the largest sum of sub-arrays that include the middle of the array.

Here's the relevant code:

lfSum = Integer.MIN_VALUE;
sum = 0;
// Sum from left to mid
for (int i = mid; i >= LF; i--) {
    sum += array[i];
    if (sum > lfSum) {
        lfSum = sum;
        if (lfSum > lfMax) {
            lfMax = lfSum;
        }
    }
}

rtSum = Integer.MIN_VALUE;
sum = 0;
// Sum from mid to right
for (int j = mid+1; j <= RT; j++) {
    sum += array[j];
    if (sum > rtSum) {
        rtSum = sum;
        if (rtSum > rtMax) {
            rtMax = rtSum;
        }
    }
}

// Largest sum spanning whole array
midMax = lfSum + rtSum; // midMax = leftMid + midRight;

What this does is it loops through each half of the entire array and checks to see if the sum is larger than the smallest integer possible in case the entire array is negative. If it is, it sets that side's max sum to sum's value. If that value is larger than what one of the recursive calls returned (lfMax or rtMax), set the respective side's recursive value to it.

Like I said earlier, this works perfectly well, but I'm not supposed to be using "Integer.MIN_VALUE". Is there another way around this? Obviously I could initialize lfSum/rtSum to the numerical value of Integer.MIN_VALUE, but I'd like to know if there are any other options.

I've tried removing rtSum/lfSum and just comparing sum to the recursive values, and initializing lfSum/rtSum to 0, but both did not work correctly. Thanks for taking the time to read this!

You can initialize lfSum as null :

Integer lfSum = null;

And modify the if condition like this:

if (lfSum == null || (lfSum != null && sum > lfSum.intValue())) {
    lfSum = sum;
    if (lfSum > lfMax) {
        lfMax = lfSum;
    }
}

Similar strategy applies to rtSum .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM