Leetcode Note: Maximum Subarray (Maximum substring and problem)

Source: Internet
Author: User

Leetcode Note: Maximum Subarray (Maximum substring and problem)

I. Description

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array[−2,1,−3,4,−1,2,1,−5,4], The contiguous subarray[4,−1,2,1]Has the largestsum = 6.

Ii. Question Analysis

You can use dynamic planning to solve the problem. The time complexity is O (n ). Assuming that0, .., kThe largest andsum[k]Later, then0, ..., k+1Sum [k + 1] is divided into the following two situations:
1) ifsum[k]>=0, Thensum[k+1]=sum[k]+A[k+1].
2) Ifsum[k]<0, Create another SubArraysum[k+1]=A[k+1].

In the calculation process, use a variablemaxsumFor storagesumThe maximum value.sumThe value is updated, and the variable is returned.

Iii. Sample Code

int maxSubArray(int A[], int n) {    if (n <= 0) return 0;    int sum = 0;    int maxsum = INT_MIN;    for (int i = 0; i < n; i++)    {        sum += A[i];        if (sum > maxsum) maxsum = sum;        if (sum < 0) sum = 0;    }    return maxsum;  }

Iv. Summary

This is a basic dynamic planning question, although there are many other ways to achieve it.

 

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.