首页 > 其他 > 详细

Maximum Subarray -- leetcode

时间:2015-03-08 11:49:30      阅读:235      评论:0      收藏:0      [点我收藏+]

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 largest sum = 6.

click to show more practice.

More practice:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.




算法一

O(n),在leetcode上实际执行时间为16ms。

class Solution {
public:
    int maxSubArray(int A[], int n) {
        if (n <= 0) return INT_MIN;
        int sum = A[0];
        int maxSum = sum;
        for (int i=1; i<n; i++) {
                sum = max(A[i], sum+A[i]);
                maxSum = max(maxSum, sum);
        }
        return maxSum;
    }
};


算法二 divide and conquer

O(nlogn), 在leetcode上实际执行时间为18ms。

class Solution {
public:
    int maxSubArray(int A[], int n) {
        if (n <= 0) return INT_MIN;
        return helper(A, 0, n-1);
    }

    int helper(int A[], int left, int right) {
        if (left == right)
                return A[left];

        const int mid = left + (right-left) / 2;
        int sum = A[mid];
        int midMax = sum;
        for (int i=mid-1; i>=left; i--) {
                sum += A[i];
                midMax = max(midMax, sum);
        }

        sum = midMax;
        for (int i=mid+1; i<=right; i++) {
                sum += A[i];
                midMax = max(midMax, sum);
        }

        const int leftMax = helper(A, left, mid);
        const int rightMax = helper(A, mid+1, right);

        return max(midMax, max(leftMax, rightMax));
    }
};

参考自:

https://oj.leetcode.com/discuss/694/how-solve-maximum-subarray-using-divide-and-conquer-approach

Maximum Subarray -- leetcode

原文:http://blog.csdn.net/elton_xiao/article/details/44131209

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!