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 has the [4,−1,2,1] 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.
[Solution]dynamic programming:let LOCAL_SUFFIX[0...I....N] Represet max Subarray contains the ith number in a[],
0) 1];else1];
1 intMaxsubarray (intA[],intN)2 {3 if(N <=0)4 return-1;5 intGlobal_suffix = int_min, *local_suffix =New int[n +1];6 7local_suffix[0] =0;8 for(inti =1; I <= N; i++)9 {Ten if(Local_suffix[i-1] <=0) OneLocal_suffix[i] = a[i-1]; A Else -Local_suffix[i] = local_suffix[i-1] + a[i-1]; - the if(Global_suffix <Local_suffix[i]) -Global_suffix =Local_suffix[i]; - } - + delete[] Local_suffix; - returnGlobal_suffix; +}
However, this uses O (n) memory. We can use just local_suffix instead.
1 intMaxsubarray (intA[],intN)2 {3 if(N <=0)4 return-1;5 intGlobal_suffix =int_min, Local_suffix;6 7 for(inti =0; I < n; i++)8 {9 if(Local_suffix <=0)TenLocal_suffix =A[i]; One Else ALocal_suffix = Local_suffix +A[i]; - - if(Global_suffix <Local_suffix) theGlobal_suffix =Local_suffix; - } - - returnGlobal_suffix; +}
Leetcode 53. Maximum Subarray