题目描述:
输入一个整形数组,数组里有正数也有负数。
数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。
求所有子数组的和的最大值。要求时间复杂度为O(n)。
例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2,
因此输出为该子数组的和18。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
public
static
void
MaxSum(
int
[] arr) {
int startSumMax = 0 ;
int endSumMax = 0 ;
int startIndex = 0 ;
int endIndex = 0 ;
int max = 0 ;
for ( int i = 0 ; i < arr.length; i ++ ) {
int startTmp = SumInt(startSumMax, arr[i]);
int endTmp = SumInt(endSumMax, arr[arr.length - 1 - i]);
if (startTmp < arr[i]) {
startIndex = i;
startSumMax = arr[i];
} else {
startSumMax = startSumMax + arr[i];
}
if (endTmp < arr[arr.length - 1 - i]) {
endIndex = arr.length - 1 - i;
endSumMax = arr[arr.length - 1 - i];
} else {
endSumMax = endSumMax + arr[arr.length - 1 - i];
}
}
if (startIndex > endIndex) {
// Error
}
for ( int i = startIndex; i < endIndex; i ++ ) {
max = max + arr[i];
}
}
int startSumMax = 0 ;
int endSumMax = 0 ;
int startIndex = 0 ;
int endIndex = 0 ;
int max = 0 ;
for ( int i = 0 ; i < arr.length; i ++ ) {
int startTmp = SumInt(startSumMax, arr[i]);
int endTmp = SumInt(endSumMax, arr[arr.length - 1 - i]);
if (startTmp < arr[i]) {
startIndex = i;
startSumMax = arr[i];
} else {
startSumMax = startSumMax + arr[i];
}
if (endTmp < arr[arr.length - 1 - i]) {
endIndex = arr.length - 1 - i;
endSumMax = arr[arr.length - 1 - i];
} else {
endSumMax = endSumMax + arr[arr.length - 1 - i];
}
}
if (startIndex > endIndex) {
// Error
}
for ( int i = startIndex; i < endIndex; i ++ ) {
max = max + arr[i];
}
}