# LintCode 45. 最大子数组差

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) {
int[][] left = new int[nums.length][2];
int leftMax = Integer.MIN_VALUE, leftMin = Integer.MAX_VALUE, leftTmp1 = 0, leftTmp2 = 0;
for (int i = 0; i < left.length - 1; i++) {
if (leftTmp1 < 0) {
leftTmp1 = nums[i];
} else {
leftTmp1 += nums[i];
}
if (leftTmp1 > leftMax) {
leftMax = leftTmp1;
}
left[i][1] = leftMax;

if (leftTmp2 > 0) {
leftTmp2 = nums[i];
} else {
leftTmp2 += nums[i];
}
if (leftTmp2 < leftMin) {
leftMin = leftTmp2;
}
left[i][0] = leftMin;
}

int[][] right = new int[nums.length][2];
int rightMax = Integer.MIN_VALUE, rightMin = Integer.MAX_VALUE, rightTmp1 = 0, rightTmp2 = 0;
for (int i = right.length - 1; i > 0; i--) {
if (rightTmp1 < 0) {
rightTmp1 = nums[i];
} else {
rightTmp1 += nums[i];
}
if (rightTmp1 > rightMax) {
rightMax = rightTmp1;
}
right[i][1] = rightMax;

if (rightTmp2 > 0) {
rightTmp2 = nums[i];
} else {
rightTmp2 += nums[i];
}
if (rightTmp2 < rightMin) {
rightMin = rightTmp2;
}
right[i][0] = rightMin;
}

int result = Integer.MIN_VALUE;
for (int i = 0; i < nums.length - 1; i++) {
int tmp1 = Math.abs(left[i][0] - right[i+1][0]);
int tmp2 = Math.abs(left[i][0] - right[i+1][1]);
int tmp3 = Math.abs(left[i][1] - right[i+1][0]);
int tmp4 = Math.abs(left[i][1] - right[i+1][1]);
int tmp = Math.max(tmp1, Math.max(tmp2, Math.max(tmp3, tmp4)));
if (tmp > result) {
result = tmp;
}
}
return result;
}
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120