[Lintcode]Maximum Subarray II 最大子數組 II

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;
    }
}



發佈了204 篇原創文章 · 獲贊 18 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章