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
.
求最大连续子序列和。
若到 i 之前的连续序列的和为正,那么 i 就接受这个和,若为负,i 就丢弃掉,从自身开始累加(就是将原来累加的和清零),然后判断当前的累积是不是不是比最大结果大,若是,则更新最大结果为当前累积和。
class Solution { public: int maxSubArray(int A[], int n) { int max = -0x7f7f7f7f; int sum = 0; for(int i = 0; i < n; ++i) { if(sum < 0) sum = 0; sum += A[i]; if(sum > max) max = sum; } return max; } };