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
.

1 class Solution { 2 public: 3 int maxSubArray(int A[], int n) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 if (0>=n) return 0; 7 8 int b = 0; 9 10 int sum =A[0]; 11 12 for(int i=0;i<n;i++){ 13 if(b<0) 14 b=0; 15 16 b = b+A[i]; 17 18 if(b>sum) 19 sum =b; 20 } 21 return sum; 22 } 23 };
思路:最大连续子数组的和,这是个非常经典的题目,答案也很简练,重点是代码中b这个变量的使用。