AC 4ms
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
.
一开时觉得挺麻烦,分配了一个数组来存储 0~n-1
所有位置的最大值,每次遇到新的正值的时候根据dp存的值和存储最大序列的下标回朔运算,最后想想,可疑把每个非负块当成一个独立的元素块,如果遇到小于0的块直接扔掉就好了,然后从下一个重新计算,记录最大值。
过程大概是这样子的
nums | −2 | 1 | -3 | 4 | −1 | 2 | 1 | −5 | 4 |
---|---|---|---|---|---|---|---|---|---|
ans | 0 | 1 | 1 | 4 | 4 | 5 | 6 | ||
sum | 0 | 1 | 0 | 4 | 3 | 5 | 6 |
int maxSubArray(int* nums, int numsSize) {
int ans=nums[0],i,j,sum=0;
for(i=0;i<numsSize;i++){
sum+=nums[i];
ans=sum>ans?sum:ans;
sum=sum>0?sum:0;
}
return ans;
}