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:13px; 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.
Dynamic planning method, if Max plus the current element is greater than the current element, the value of Max is the current element plus max when the current element is added to the array. If it is less than the current element, Max is the current element when the current element is added to the array.
Class Solution {public: int maxsubarray (int a[], int n) {if (n = = 0) return-1;if (n = = 1) return A[0];int max = A[0];int res = max;for (int i=1; i<n; i++) {if (max > 0) max = a[i] + max;else max = a[i];if (Max > Res) res = max;} return res; }};
Leetcode--maximum Subarray