[Leetcode]: 53:maximum subarray

Source: Internet
Author: User

Topic:

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.

Analysis:

-Using dynamic programming ideas

Calculates the largest and the first n items, and the result may be as follows for newly added n+1 items

N=0: For maximum and no help

Separate a[n+1]

The resulting array is combined with Max_subarray (A[n]) and a[n+1] and the elements between them.

Among them, if in the growth process, the existing array segment and is negative, can be discarded immediately, because in this case, max_subarray if the inclusion of this paragraph, the value will certainly be greater than excluding this paragraph.

Code:

     Public Static intMaxsubarray (int[] nums) {        intIntresult = Nums[0]; intIntcurrentsum = Nums[0];  for(intI =1;i<nums.length;i++){            if(Intcurrentsum < 0) {intcurrentsum=Nums[i]; }            Else{intcurrentsum= Intcurrentsum +Nums[i]; }                        if(intcurrentsum>intresult) {Intresult=intcurrentsum; }        }                 returnIntresult; }

[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.