关闭

#42 Maximum Subarray II

标签: lintcodedynamic programming
53人阅读 评论(0) 收藏 举报
分类:

题目描述:

Given an array of integers, find two non-overlapping subarrays which have the largest sum.
The number in each subarray should be contiguous.
Return the largest sum.

 Notice

The subarray should contain at least one number

Example

For given [1, 3, -1, 2, -1, 2], the two subarrays are [1, 3]and [2, -1, 2] or [1, 3, -1, 2] and [2], they both have the largest sum 7.

Challenge 

Can you do it in time complexity O(n) ?

题目思路:

这题基于#41的基础上有所扩展:可以用#41的算法,对于每个i,都算出它左边subarray中的最大值和右边subarray中的最大值。然后再重新遍历一遍原来的数组,找到所有的i中两边最大值相加最大就可以了。

Mycode(AC = 33ms):

class Solution {
public:
    /**
     * @param nums: A list of integers
     * @return: An integer denotes the sum of max two non-overlapping subarrays
     */
    int maxTwoSubArrays(vector<int> nums) {
        // write your code here
        if (nums.size() <= 1) return 0;
        
        vector<int> left_max(nums), right_max(nums);
        
        // get max for subarray indexed 0...i
        int local = nums[0];
        for (int i = 1; i < nums.size(); i++) {
            local = max(local + nums[i], nums[i]);
            left_max[i] = max(left_max[i - 1], local);
        }
        
        // get max for subarray indexed i...nums.size() - 1
        local = nums[nums.size() - 1];
        for (int i = nums.size() - 2; i >= 0; i--) {
            local = max(local + nums[i], nums[i]);
            right_max[i] = max(right_max[i + 1], local);
        }
        
        // get final result
        int global = INT_MIN;
        for (int i = 1; i < nums.size(); i++) {
            global = max(global, left_max[i - 1] + right_max[i]);
        }
        return global;
    }
};


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:12393次
    • 积分:2244
    • 等级:
    • 排名:第16803名
    • 原创:221篇
    • 转载:1篇
    • 译文:0篇
    • 评论:10条
    文章分类
    文章存档