[LintCode] Maximum Subarray II

http://www.lintcode.com/zh-cn/problem/maximum-subarray-ii/#

对所有的i,分别计算区间[0...i][i+1...n-1]的最大值,取相加最大的。不要同时计算,分别预处理好是O(n)。

int maxTwoSubArrays(vector<int> &nums) {
    if (nums.empty()) return 0;
    
    int n = nums.size();
    vector<int> left(n);
    vector<int> right(n);
    
    left[0] = nums[0];
    int prev = nums[0], cur;
    for (int i = 1; i < n - 1; ++i) {
        if (prev > 0) cur = prev + nums[i];
        else cur = nums[i];
        left[i] = max(left[i-1], cur);
        prev = cur;
    }
    
    right[n-1] = nums[n-1];
    prev = nums[n-1], cur;
    for (int i = n - 2; i > 0; --i) {
        if (prev > 0) cur = prev + nums[i];
        else cur = nums[i];
        right[i] = max(right[i+1], cur);
        prev = cur;
    }
    
    int ret = -0x3f3f3f3f;
    for (int i = 0; i < n-1; ++i) {
        ret = max(ret, left[i] + right[i+1]);
    }
    return ret;
}
posted @ 2017-09-12 22:35  mioopoi  阅读(138)  评论(0编辑  收藏  举报