【Leetcode】Maximum Subarray

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.

方法一:时间复杂度O(n),空间复杂度O(1)

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


方法二:分治法,以中间数为结点将序列分为三段:前半段的最大值,后半段的最大值以及前半段+中间数+后半段的最大值;时间复杂度O(nlgn)

class Solution {
public:
    int maxSubArray(int A[], int n) {
        
        if(n <= 0)  return 0;
        
        return maxSubArraySolver(A, 0, n-1);
    }
    
private:
    int maxSubArraySolver(int A[], int l, int r)
    {
        if(l == r)  return A[l];
        
        int m = (l + r) / 2;
        int leftmax = maxSubArraySolver(A, l, m);
        int rightmax = maxSubArraySolver(A, m + 1, r);
        
        int templeftmax = A[m];
        int temp = 0;
        for(int i = m; i >= l; i--)
        {
            temp += A[i];
            if(temp > templeftmax)
                templeftmax = temp;
        }
        
        int temprightmax = A[m + 1];
        temp = 0;
        for(int i = m + 1; i <= r; i++)
        {
            temp += A[i];
            if(temp > temprightmax)
                temprightmax = temp;
        }
        
        return max(max(leftmax, rightmax), templeftmax + temprightmax);
    }
};

方法三:动态规划,时间复杂度O(n),空间复杂度O(1)。

定义b[j]为数组中包含A[j]的最大连续子序列和,注意一个误区,b[j] 并不是要求的最大的连续子序列的和,只是包含A[j]的最大子序列的和而我们所要求的则是b[j]中最大的值。因此状态方程为: b[j] = max(b[j-1] + A[j] , A[j]),在实现中直接用变量count对b数组求最大值了。

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


你可能感兴趣的:(【Leetcode】Maximum Subarray)