Maximum Subarray Difference(最大子数组差)

http://www.lintcode.com/zh-cn/problem/maximum-subarray-difference/

public class Solution {
    /*
     * @param nums: A list of integers
     * @return: An integer indicate the value of maximum difference between two substrings
     */
    public int maxDiffSubArrays(int[] nums) {
        // write your code here
        Node[] left = new Node[nums.length];
        Node[] right = new Node[nums.length];
//        依次记录下来从左向右每个位置的最大值和最小值,然后从右向左的
//        从每个位置分左右,两边的四个值做两组减法,然后取最大值
        int singleMax = 0;
        int singleMin = 0;
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length; i++) {
            singleMax = Math.max(nums[i], singleMax + nums[i]);
            max = Math.max(singleMax, max);
            singleMin = Math.min(nums[i], singleMin + nums[i]);
            min = Math.min(singleMin, min);
            left[i] = new Node(max, min);
        }
        singleMax = 0;
        singleMin = 0;
        max = Integer.MIN_VALUE;
        min = Integer.MAX_VALUE;
        int res = Integer.MIN_VALUE;
        for (int i = nums.length - 1; i > 0; i--) {
            singleMax = Math.max(nums[i], singleMax + nums[i]);
            max = Math.max(singleMax, max);
            singleMin = Math.min(nums[i], singleMin + nums[i]);
            min = Math.min(singleMin, min);
            int temp = Math.max(Math.abs(left[i - 1].max - min), Math.abs(left[i - 1].min - max));
            res = Math.max(res, temp);
        }
        return res;
    }

    private class Node {
        int max;
        int min;

        public Node(int max, int min) {
            this.max = max;
            this.min = min;
        }
    }
}

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