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.
Example
For [1, 2, -3, 1]
, return 6
.
leftMin[i] = Math.min(leftMin[i - 1], Math.min(nums[i] + min, nums[i])); leftMin代表0到i处(包括)连续最小子字符串和。其等于index=i-1时leftMin的值,或者包含或者不包含nums[i]的sum。
最后遍历一次计算leftMin和rightMax 或者leftMax和rightMin的绝对值的最大值。注意错位求和。
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) {
int[] leftMin = new int[nums.length];
int[] leftMax = new int[nums.length];
//i向前连续n项元素的和
int min = 0, max = 0;
for(int i = 0; i < nums.length; i++) {
min = Math.min(nums[i] + min, nums[i]);
max = Math.max(nums[i] + max, nums[i]);
if(i == 0) {
leftMin[i] = min;
leftMax[i] = max;
} else {
leftMin[i] = Math.min(leftMin[i - 1], min);
leftMax[i] = Math.max(leftMax[i - 1], max);
}
}
int res = 0, endMin = 0, endMax = 0;
min = 0;max = 0;
for(int i = nums.length - 1; i > 0; i--) {
min = Math.min(nums[i] + min, nums[i]);
max = Math.max(nums[i] + max, nums[i]);
if(i == nums.length - 1) {
endMin = min;
endMax = max;
} else {
endMin = Math.min(endMin, min);
endMax = Math.max(endMax, max);
}
res = Math.max(Math.max(Math.abs(leftMax[i-1]-endMin),
Math.abs(endMax - leftMin[i-1])), res);
}
return res;
}
}