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

Maximum Subarray -- leetcode

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

标签:leetcode   面试   最大和   

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

标签:leetcode   面试   最大和   

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

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