Lintcode - Maximum Subarray II

30 篇文章 0 订阅
29 篇文章 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.

Note

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.

思路和股票买卖III一样:

分层两段,左边和右边分别计算max subarray,然后两边加起来最大的就是结果。

这道题目里没有明确说一定要两段(比如一段可不可以,比如左边没有值,右边有一段),但是实际结果是一段是不可以的。。。

    public int maxTwoSubArrays(ArrayList<Integer> nums) {
        int[] left = new int[nums.size()];

        int localMax = 0;
        int globalMax = Integer.MIN_VALUE;
        for (int i = 0; i < nums.size(); i++) {
            localMax = Math.max(nums.get(i), localMax + nums.get(i));
            globalMax = Math.max(localMax, globalMax);
            left[i] = globalMax;
        }
        
        localMax = 0;
        globalMax = Integer.MIN_VALUE;
        int result = Integer.MIN_VALUE;
        for (int i = nums.size()-1; i >= 0; i--) {
            if (i < nums.size()-1) {
                result = Math.max(result, left[i] + globalMax);
            }
            localMax = Math.max(nums.get(i), localMax + nums.get(i));
            globalMax = Math.max(localMax, globalMax);
        }
        return result;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值