标签:
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 if(n<=0) return 0; 5 6 int sum=0; 7 int max=INT_MIN; 8 9 10 for(int i=0;i<n;i++) 11 { 12 sum+=A[i]; 13 if(sum>max) max=sum; 14 if(sum<0) sum=0; 15 16 } 17 return max; 18 } 19 };
More Practice 分治法:
1 int myMaxSubArray(int A[], int m, int n) 2 { 3 if (m == n) return A[m]; 4 5 int mid = (m+n)/2; 6 int maxPre = myMaxSubArray(A, m, mid); 7 int maxEnd = myMaxSubArray(A, mid+1, n); 8 9 int leftMax = INT_MIN; 10 int rightMax = INT_MIN; 11 int sum = 0; 12 for (int i = mid; i >= m; i--) 13 { 14 sum += A[i]; 15 if (sum > leftMax) 16 leftMax = sum; 17 } 18 sum = 0; 19 for (int i = mid+1; i <=n; i++) 20 { 21 sum += A[i]; 22 if (sum > rightMax) 23 rightMax = sum; 24 } 25 sum = leftMax + rightMax; 26 27 return std::max(sum, std::max(maxPre, maxEnd)); 28 } 29 30 int maxSubArray(int A[], int n) 31 { 32 if (n <= 0) return 0; 33 34 return myMaxSubArray(A, 0, n-1); 35 }
标签:
原文地址:http://www.cnblogs.com/jawiezhu/p/4437958.html