码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode "Maximum Subarray"

时间:2014-07-21 11:06:21      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   os   io   

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 !

LeetCode "Maximum Subarray",布布扣,bubuko.com

LeetCode "Maximum Subarray"

标签:des   style   blog   color   os   io   

原文地址:http://www.cnblogs.com/tonix/p/3857651.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!