【题目】
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
.
这道题是求连续子数组的最大和,开始我还想复杂了,其实直接从开始向后加就好了,如果和大于零就继续加,和小于零就从下一位开始加。
【代码】
public int maxSubArray(int[] nums) {
int n=nums.length;
int max=nums[0],sum=max;
for(int i=1;i<n;i++){
if(sum>0) sum+=nums[i];
else sum=nums[i];
if(max<sum) max=sum;
}
return max;
}