Find the contiguous subarray within an array (containing at least one number) which have the largest sum.
for example, given the Array [?2,1,?3,4,?1,2,1,?5,4"
,
the contiguous subarray < Code style= "Font-family:menlo,monaco,consolas, ' Courier New ', monospace; font-size:12.6000003814697px; PADDING:2PX 4px; Color:rgb (199,37,78); Background-color:rgb (249,242,244) ">[4,?1,2,1" has the largest sum = 6
.
Click to show more practice.
More Practice:
If you had figured out the O (n) solution, try coding another solution using the divide and conquer approach, WHI CH is more subtle.
Algorithm One
O (n), the actual execution time on the Leetcode is 16ms.
Class Solution {public: int maxsubarray (int a[], int n) { if (n <= 0) return int_min; int sum = a[0]; int maxsum = sum; for (int i=1; i<n; i++) { sum = max (A[i], sum+a[i]); Maxsum = max (maxsum, sum); } return maxsum;} ;
Algorithm two divide and conquer
O (Nlogn), the actual execution time on the Leetcode is 18ms.
Class Solution {public: int maxsubarray (int a[], int n) { if (n <= 0) return int_min; Return helper (A, 0, n-1); } int helper (int a[], int left, int.) { if (left = right) return a[left]; const int MID = left + (right-left)/2; int sum = A[mid]; int midmax = sum; for (int i=mid-1; i>=left; i--) { sum + = A[i]; Midmax = max (Midmax, sum); } sum = Midmax; for (int i=mid+1; i<=right; i++) { sum + = A[i]; Midmax = max (Midmax, sum); } const int Leftmax = Helper (A, left, mid); const int Rightmax = Helper (A, mid+1, right); Return Max (Midmax, Max (Leftmax, Rightmax));} ;
Reference from:
Https://oj.leetcode.com/discuss/694/how-solve-maximum-subarray-using-divide-and-conquer-approach
Maximum Subarray--Leetcode