首页 > 代码库 > LeetCode "Maximum Subarray"

LeetCode "Maximum Subarray"

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[0];        int sum = A[0];        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 !