Leetcode 53. Maximum Subarray

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.