首页 > 其他 > 详细

lintcode-medium-Maximum Subarray II

时间:2016-03-30 14:34:15      阅读:175      评论:0      收藏: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) ?

 

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 == null || nums.size() == 0)
            return 0;
        
        int size = nums.size();
        
        int sum = nums.get(0);
        int[] l2r = new int[size];
        int[] r2l = new int[size];
        l2r[0] = nums.get(0);
        r2l[size - 1] = nums.get(size - 1);
        
        for(int i = 1; i < size; i++){
            if(sum < 0)
                sum = 0;
            
            sum += nums.get(i);
            
            if(sum > l2r[i - 1])
                l2r[i] = sum;
            else
                l2r[i] = l2r[i - 1];
        }
        
        sum = nums.get(size - 1);
        
        for(int i = size - 2; i >= 0; i--){
            if(sum < 0)
                sum = 0;
            
            sum += nums.get(i);
            
            if(sum > r2l[i + 1])
                r2l[i] = sum;
            else
                r2l[i] = r2l[i + 1];
        }
        
        int result = Integer.MIN_VALUE;
        
        for(int i = 0; i < size - 1; i++)
            result = Math.max(result, l2r[i] + r2l[i + 1]);
        
        return result;
    }
}

 

lintcode-medium-Maximum Subarray II

原文:http://www.cnblogs.com/goblinengineer/p/5336754.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!