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.

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)方法:

class Solution {
public:
    int maxSubArray(int A[], int n) {
        int sum = 0;
        int largest = numeric_limits<int>::min();
        for (int i = 0; i < n; ++i) {
            sum += A[i];
            if (sum > largest) {
                largest = sum;
            }
            if (sum < 0) {
                sum = 0;
            }
        }
        
        return largest;
    }
};
分治方法:

class Solution {
public:
    int maxSubArray(int A[], int n) {
       
        return maxSubArrayUtil(A, 0 , n - 1);
    }
    
    int maxSubArrayUtil(int A[], int low, int up) {
        if (low == up) {
            return A[low];
        }
        else {
            int mid = (low + up) >> 1;
            int max_sum = max(maxSubArrayUtil(A, low, mid), maxSubArrayUtil(A, mid+1, up));
            
            int sum = 0;
            int max_low = numeric_limits<int>::min();
            for (int i = mid; i >= low; --i) {
                sum += A[i];
                if (sum > max_low) {
                    max_low = sum;
                }
            }
            sum = 0;
            int max_up = numeric_limits<int>::min();
            for (int i = mid + 1; i <= up; ++i) {
                sum += A[i];
                if (sum > max_up) {
                    max_up = sum;
                }
            }
            
            return max(max_sum, max_low + max_up);
        }
    }
};

按理说,分治方法时间复杂度为O(nlgn),但测试用例时间花费反而小一些。可能跟测试集合有关系吧。

你可能感兴趣的:(LeetCode)