# Leetcode "Maximum subarray"

Source: Internet
Author: User

Very classic problem. You can brush up your DP and searching skills.

DP:

`class Solution {public:    int maxSubArray(int A[], int n) {        // dp[i + 1] = max(dp[i] + A[i], A[i]);        //int start = 0, end = 0;        int max = A;        int sum = A;        for (int i = 1; i < n; i++)        {            if (A[i] >(sum + A[i]))            {                sum = A[i];                //if (sum > max) start = i;            }            else            {                sum = (sum + A[i]);                //if (sum > max) end = i;            }            max = sum > max ? sum : max;        }        return max;    }};`

Equation: DP [I + 1] = max (DP [I] + A [I + 1], a [I + 1]). in case subarray location is needed, please check the commented lines.

And it is brand new to me as a rookie that it can also be solved by binary search! We get 3 values: Result of 1st half, result of 2nd half, and 3rd is the cross boundary case:

`class Solution {public:    int bigger(int a, int b)    {        return a > b ? a : b;    }    int solve(int A[], int start, int end)    {        if (start == end) return A[start];        int mid = start + (end - start) / 2;        int leftMax = solve(A, start, mid);        int rightMax = solve(A, mid + 1, end);        //    cross boundary?        int sum0 = A[mid],    cMaxL = A[mid];        for (int i = mid - 1; i >= start; i--)        {            sum0 += A[i];            cMaxL = bigger(sum0, cMaxL);        }        int sum1 = A[mid + 1], cMaxR = A[mid + 1];        for (int i = mid + 2; i <= end; i++)        {            sum1 += A[i];            cMaxR = bigger(sum1, cMaxR);        }        return bigger(bigger(leftMax, rightMax), cMaxL + cMaxR);    }    int maxSubArray(int A[], int n) {        return solve(A, 0, n-1);    }};`

Deserve To revise later!

Related Keywords:

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.