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,则在后面的数加上现在的和只会比原来的数要小,故舍弃

1 class Solution { 2 public: 3 int maxSubArray(int A[], int n) { 4 int ans = 0; 5 int maxsum = INT_MIN; 6 7 for (int i = 0; i < n; i++) 8 { 9 if (ans < 0) 10 ans = 0; 11 ans += A[i]; 12 maxsum = max(ans, maxsum); 13 } 14 return maxsum; 15 } 16 };
原文:http://www.cnblogs.com/bournet/p/4108624.html