简体   繁体   English

子阵列最大和

[英]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. 如果该值大于一个递归调用返回的值(lfMax或rtMax),则将相应端的递归值设置为该值。

Like I said earlier, this works perfectly well, but I'm not supposed to be using "Integer.MIN_VALUE". 就像我之前说的那样,这很好用,但是我不应该使用“ 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. 显然,我可以将lfSum / rtSum初始化为Integer.MIN_VALUE的数值,但是我想知道是否还有其他选项。

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. 我尝试删除rtSum / lfSum并仅将sum与递归值进行比较,然后将lfSum / rtSum初始化为0,但两者均无法正常工作。 Thanks for taking the time to read this! 感谢您抽时间阅读!

You can initialize lfSum as null : 您可以将lfSum初始化为null

Integer lfSum = null;

And modify the if condition like this: 并修改if条件,如下所示:

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

Similar strategy applies to rtSum . 类似的策略适用于rtSum

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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