题目描述
输入一个整型数组,数组里有正数也有负数。数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。要求时间复杂度为 O(n).
示例1
输入
[1,-2,3,10,-4,7,2,-5]
返回值
18
说明
输入的数组为{1,-2,3,10,—4,7,2,一5},和最大的子数组为{3,10,一4,7,2},因此输出为该子数组的和 18。
在线链接
代码:
public class Solution {
public int FindGreatestSumOfSubArray(int[] array) {
if(array == null || array.length == 0){
return 0;
}
int ans = 0;
int max = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
ans += array[i];
max = Math.max(max,ans);
if(ans < 0){
ans = 0;
}
}
return max;
}
}
思路概述:
我们累加数组元素,并用max来记录最大的那个累加和。累加过程中可能遇到结果变成了负数,那这个和如果继续与之后的元素累加,反而会导致后半部分的和变小,所以变成负数后就让结果变为0,重新累加。