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
.
More practice:
If you have figured out the O (N) Solution, try coding another solution using the divide and conquer approach, which is more subtle.
The most stupid way is to calculate all the results of the sum of all I numbers (1 <= I <= N) and return the largest number.
But in leetcode, time limit exceeded is often done !! The following is an example of how to make an effort: (the result is correct)
Int maxsubarray (int A [], int N) {int max = A [0]; for (INT I = 1; I <= N; I ++) // sum of I count {for (Int J = 0; j <= n-I; j ++) // start position of the number of consecutive additions J {int sum = 0; int J0 = J; For (int K = 1; k <= I; k ++) sum + = A [J0 ++]; If (max <sum) max = sum ;}} return Max ;}
Therefore, we need to consider a simple method.
1) kadane algorithm (Linear Time Algorithm), see http://blog.csdn.net/joylnwang/article/details/6859677
2) Dynamic Planning
3) divide (this is the algorithm required by leetcode)
~~~~ Implement each algorithm ~ (The following are the classic practices discussed in leetcode)
Method 1:
class Solution { public: int maxSubArray(int A[], int n) { int s[n]; int max = s[0] = A[0]; for (int i = 1; i < n; i++) { s[i] = s[i-1] > 0 ? (A[i] + s[i-1]) : A[i]; max = std::max(max, s[i]); } return max; }};
Method 2: divide
Step1. select the middle element of the array. So the maximum subarray may contain that middle element or not.
Step 2.1 If the maximum subarray does not contain the middle element, then we can apply the same algorithm to the subarray to the left of the middle element and the subarray to the right of the middle element.
Step 2.2 If the maximum subarray does contain the middle element, then the result will be simply the maximum suffix subarray of the Left subarray plus the maximum prefix subarray of the right subarray
Step 3 return the maximum of those three answer.
Here is a sample code for divide and conquer solution. Please try to understand the algorithm before look at the code
class Solution {public: int maxSubArray(int A[], int n) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(n==0) return 0; return maxSubArrayHelperFunction(A,0,n-1); } int maxSubArrayHelperFunction(int A[], int left, int right) { if(right == left) return A[left]; int middle = (left+right)/2; int leftans = maxSubArrayHelperFunction(A, left, middle); int rightans = maxSubArrayHelperFunction(A, middle+1, right); int leftmax = A[middle]; int rightmax = A[middle+1]; int temp = 0; for(int i=middle;i>=left;i--) { temp += A[i]; if(temp > leftmax) leftmax = temp; } temp = 0; for(int i=middle+1;i<=right;i++) { temp += A[i]; if(temp > rightmax) rightmax = temp; } return max(max(leftans, rightans),leftmax+rightmax); }};