给定一个整数数组 nums?,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2, 1, -3, 4, -1, 2, 1, -5, 4],
输出: 6
解释:?连续子数组?[4,-1,2,1] 的和最大,为?6。
public int maxSubArray(int[] nums) {
int max = nums[0];
int res = 0;
for (int i = 0;i < nums.length; i++){
if(res > 0){
// 如果为正数,则可能存在增益,使得res子列存在更大值
res += nums[i];
}else{
// 如果是负数,则一直都是负数比较
res = nums[i];
}
max = Math.max(max, res);
}
return max;
}
原文:https://www.cnblogs.com/athony/p/13029238.html