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.
Problem Solving report: Kadane algorithm, complexity O (n).
Class Solution {public: int maxsubarray (int a[], int n) { int max_so_far = a[0]; int max_ending_here = 0; for (int i = 0; I! = N; i++) { Max_ending_here = Max_ending_here + a[i]; if (Max_so_far < max_ending_here) Max_so_far = Max_ending_here; if (Max_ending_here < 0) max_ending_here = 0; } return max_so_far;} ;
Leetcode-maximum Subarray