Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4]
,
the contiguous subarray [4,-1,2,1]
has the largest sum = 6
.
思路:如果cursum < 0,那么立刻不要了,当前重新reset成当前的num,继续求cursum;
class Solution {
public int maxSubArray(int[] nums) {
int maxsum = nums[0];
int cursum = nums[0];
for(int i = 1; i < nums.length; i++) {
if(cursum < 0) {
cursum = nums[i];
} else {
cursum += nums[i];
}
maxsum = Math.max(maxsum, cursum);
}
return maxsum;
}
}