[lintcode medium]Maximum Subarray II

Maximum Subarray 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.

Note

The subarray should contain at least one number

Challenge

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

 

与买卖股票的思路一样,从两边分别计算最大子串

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) {
        // write your code
        if(nums.size()==0 || nums==null) return 0;
        int n=nums.size();
        int result=Integer.MIN_VALUE;;
        
        int[] preSum=new int[n];
        
        int sum1=0;
        int max=Integer.MIN_VALUE;
        for(int i=0;i<n;i++)
        {
            sum1=Math.max(sum1+nums.get(i),nums.get(i));
            max=Math.max(max,sum1);
            preSum[i]=max;
        }
        
        max=Integer.MIN_VALUE;
        int sum2=0;
        for(int i=n-1;i>=0;i--)
        {
            if(i<n-1)
            {
                result=Math.max(result,preSum[i]+max);
            }
            sum2=Math.max(sum2+nums.get(i),nums.get(i));
            max=Math.max(max,sum2);
        }
        return result;
    }
}

 

posted on 2015-12-18 03:52  一心一念  阅读(233)  评论(0编辑  收藏  举报

导航