in LintCode Algorithm Array Dynamic Programming ~ read.

Maximum Subarray Difference

LintCode-45.Maximum Subarray Difference

Given an array with integers.

Find two non-overlapping subarrays A and B, which |SUM(A) - SUM(B)| is the largest.

Return the largest difference.

Notice: The subarray should contain at least one number

Example: For [1, 2, -3, 1], return 6.

Challenge: O(n) time and O(n) space.

public class Solution {  
    /**
     * @param nums: A list of integers
     * @return: An integer indicate the value of maximum difference between two
     *          Subarrays
     */
    public int maxDiffSubArrays(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int[] leftMin = new int[nums.length];
        leftMin[0] = nums[0];
        int minSum = nums[0];

        int[] leftMax = new int[nums.length];
        leftMax[0] = nums[0];
        int maxSum = nums[0];

        for (int i = 1; i < nums.length; i++) {
            minSum = Math.min(minSum + nums[i], nums[i]);
            leftMin[i] = Math.min(minSum, leftMin[i - 1]);

            maxSum = Math.max(maxSum + nums[i], nums[i]);
            leftMax[i] = Math.max(maxSum, leftMax[i - 1]);
        }

        int[] rightMin = new int[nums.length];
        rightMin[nums.length - 1] = nums[nums.length - 1];
        minSum = nums[nums.length - 1];

        int[] rightMax = new int[nums.length];
        rightMax[nums.length - 1] = nums[nums.length - 1];
        maxSum = nums[nums.length - 1];

        for (int i = nums.length - 2; i >= 0; i--) {
            minSum = Math.min(minSum + nums[i], nums[i]);
            rightMin[i] = Math.min(minSum, rightMin[i + 1]);

            maxSum = Math.max(maxSum + nums[i], nums[i]);
            rightMax[i] = Math.max(maxSum, rightMax[i + 1]);
        }

        int maxDiff = 0;
        for (int i = 0; i < nums.length - 1; i++) {
            maxDiff = Math.max(maxDiff, Math.max(Math.abs(leftMax[i] - rightMin[i + 1]), Math.abs(leftMin[i] - rightMax[i + 1])));
        }

        return maxDiff;
    }
}

Hope this helps,
Michael