[Lintcode]Maximum Subarray II 最大子数组 II

来源:互联网 发布:大数据产品分析 编辑:程序博客网 时间:2024/05/18 12:01
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.

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.

分析:与最大子数组I问题类似。

public class Solution {    /**     * @param nums: A list of integers     * @return: An integer denotes the sum of max two non-overlapping subarrays     */    public int maxTwoSubArrays(ArrayList<Integer> nums) {        int[] leftMax = new int[nums.size()];        int max = 0;        for(int i = 0; i < nums.size(); i++) {            max = Math.max(nums.get(i), nums.get(i) + max);            if(i == 0) leftMax[i] = max;            else leftMax[i] = Math.max(leftMax[i - 1], max);        }                int res = Integer.MIN_VALUE;        max = 0;        for(int i = nums.size() - 1; i > 0; i--) {            max = Math.max(nums.get(i), nums.get(i) + max);            res = Math.max(res, max + leftMax[i - 1]);        }        return res;    }}


0 0
原创粉丝点击