从0开始,用count记录某个索引开始到当前数的元素和;
res记录当前最大结果;
一旦count小于0,后面无论什么,都会受影响变得更小;
不加这部分内容最大,直接跳过这部分遍历。
class Solution {
public int maxSubArray(int[] nums) {
if(nums.length < 2){
return nums[0];
}
int startIndex = 0;
int count = 0;
int res = Integer.MIN_VALUE;
for(int i = startIndex;i < nums.length;i++){
if(count < 0){
count = 0;
startIndex = i + 1;
}
count += nums[i];
res = Math.max(res,count);
}
return res;
}
}