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
.
最大连续子数组和,很简单的一个问题,三种解法,最好的是O(n)的。
1 class Solution { 2 public: 3 int maxSubArray(int A[], int n) { 4 int sum = A[0] , maxSum = A[0]; 5 for(int i = 1; i < n; i++){ 6 if(sum < 0) sum = 0; 7 sum += A[i]; 8 maxSum = maxSum<sum?sum:maxSum; 9 } 10 return maxSum; 11 } 12 };