Leetcode Maximum subarray**

Source: Internet
Author: User

Title: Maximum Subarray

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 .

Links: https://leetcode.com/problems/maximum-subarray/

Analysis: This is the sum of the maximal contiguous string, or the largest contiguous subarray of sums.

The simplest of the problem is violence, but the violence is O (n^2), timed out. In addition, dynamic programming can be used to solve the problem, the key is how to convert to dynamic programming, that is, how to express the dynamic programming problem.

we use local[i] to denote the maximum sum of successive sub-arrays ending with a[i] , then local[0] = a[0], local[1] equals either local[0]+a[1] or equals a[1] itself, the key to look at the two who are bigger, So we get recursive local[i+1] = max (Local[i]+a[i], a[i]),,,, The maximum value in the local array is the request. The iterative process does not require an array so the time complexity is O (N) and the spatial complexity is O (1).

Class Solution {public:    int maxsubarray (int a[], int n) {        if (n = = 0) return 0;        int sum = a[0];         Contiguous subarray and maximum value        int maxresult = a[0] ending with a[0];        for (int i = 1; i < n; i++) {            sum = max (a[i],a[i]+sum);      Continuous sub-array and maximum            if (Maxresult < sum) ending with a[i] maxresult = sum;         }        return maxresult;}    ;


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.