[LintCode]Maximum Subarray Difference

http://www.lintcode.com/en/problem/maximum-subarray-difference/#

求两个不重叠的子数组差值的最大值



两次遍历,从左到右和从右到左。用两个数组leftMin[i], LeftMax[i]保存左侧到当前位置i的最大子数组和最小子数组的值,再从右往左遍历找到右侧当前位置的最大子数组和最小子数组的值。

public class Solution {
    public int maxDiffSubArrays(int[] nums) {
        // write your code here
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int n = nums.length;
        int[] leftMin = new int[n + 1];
        int[] leftMax = new int[n + 1];
        leftMin[0] = Integer.MAX_VALUE;
        leftMax[0] = Integer.MIN_VALUE;
        int curMin = 0;
        int curMax = 0;
        for (int i = 0; i < n; i++) {
            curMin = Math.min(nums[i], curMin + nums[i]);
            curMax = Math.max(nums[i], curMax + nums[i]);
            leftMax[i + 1] = Math.max(leftMax[i], curMax);
            leftMin[i + 1] = Math.min(leftMin[i], curMin);
        }
        int res = 0;
        curMin = 0;
        curMax = 0;
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        for (int i = n - 1; i > 0; i--) {
            curMax = Math.max(nums[i], curMax + nums[i]);
            curMin = Math.min(nums[i], curMin + nums[i]);
            max = Math.max(max, curMax);
            min = Math.min(min, curMin);
            res = Math.max(res, Math.max(Math.abs(max - leftMin[i]), Math.abs(leftMax[i] - min)));
        }
        return res;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值