Leetcode 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 < Code style= "Font-family:menlo,monaco,consolas, ' Courier New ', monospace; font-size:12.6000003814697px; 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.

Test instructions: Maximum consecutive subsequence and.

Idea: For each number if you join it at this time sum<0 words, then let sum= at this time this number, if more than 0 words, then add it can get maximum value, compare to get results

<pre name= "code" class= "CPP" >class solution {public:    int maxsubarray (int a[], int n) {        int ans = int_min, su m = int_min;        for (int i = 0; i < n; i++) {            sum = Sum < 0? A[i]: a[i] + sum;            if (Sum > ans)                 ans = sum;        }               return ans;    };




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