Maximum Subarray II(最大子数组 II)

http://www.lintcode.com/en/problem/maximum-subarray-ii/?rand=true
请参阅 Binary Tree Maximum Path Sum(二叉树中的最大路径和)

import java.util.List;

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

你可能感兴趣的:(Maximum Subarray II(最大子数组 II))