地址:http://oj.leetcode.com/problems/maximum-subarray/
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
.
对于某个数A[i],若A[0]到A[i-1]的和大于等于0(其实处理后肯定大于等于0),则加上本身的值为sum,sum与max比较,比max大则赋值给max,若sum小于0(其实就是本身小于0),则sum赋为0。sum这样的设置保证了连续字串大于0的所有出现。
参考代码:
class Solution {
public:
int maxSubArray(int A[], int n) {
int maxsum = A[0], sum=0;
for(int i = 0; i < n; ++i)
{
sum += A[i];
maxsum = maxsum >= sum ? maxsum : sum;
if(sum < 0)
{
sum = 0;
}
}
return maxsum;
}
};