我认为你可以这样迭代:
MaxSum = 0;
CurrentSum = 0;
MaxLen = 0;
CurrentLen = 0;
Index = GetFirstPositiveValue();
// This function returns the first Index where Array[Index] > 0
// O(n)
while (Index < Array.Length()) {
// general loop to parse the whole array
while (Array[Index] > 0 && Index < Array.Length()) {
CurrentSum += Array[Index];
CurrentLen++;
Index++
}
// We computed a sum of positive integer, we store the values
// if it is higher than the current max
if (CurrentSum > MaxSum) {
MaxSum = CurrentSum;
MaxLen = CurrentLen;
}
// We reset the current values only if we get to a negative sum
while (Array[Index] < 0 && Index < Array.Length()) {
CurrentSum += Array[Index];
CurrentLen++;
Index++;
}
//We encountered a positive value. We check if we need to reset the current sum
if (CurrentSum < 0) {
CurrentSum = 0;
CurrentLen = 0;
}
}
// At this point, MaxLen is what you want, and we only went through
// the array once in the while loop.
从第一个正面元素开始。如果每个元素都是负数,那么就选择最高的,问题就结束了,这是一个1元素序列。
只要我们有正值,我们就会继续求和,所以我们有一个当前的最大值。当我们有负数时,我们检查当前最大值是否高于存储的最大值。如果是这样,我们将存储的最大值和序列长度替换为新值。
现在,我们对负数求和。当我们发现另一个阳性时,我们必须检查一下:
如果当前总和是正数,那么我们仍然可以使用这个序列获得最大总和。如果它是负数,那么我们可以丢弃当前的总和,因为最大总和不会包含它:
在{1,-2,3,4}中,3+4大于1-2+3+4
只要我们没有遍历整个数组,我们就会重新开始这个过程。只有当我们有一个产生负和的子序列时,我们才会重置序列,并且只有当我们有更大的值时才会存储最大值。
我认为这按预期工作,我们只遍历数组一两次。所以它是 O(n)
我希望这是可以理解的,我很难说清楚我的想法。使用 {1,2,3,-4,5} / {1,2,3,-50,5} / {1,2,3,-50,4,5} 等小示例执行此算法可能会有所帮助如果我不够清楚:)