LintCode 45. 最大子数组差

给定一个整数数组,找出两个不重叠的子数组A和B,使两个子数组和的差的绝对值|SUM(A) - SUM(B)|最大。

返回这个最大的差值。

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
      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;
   }
}

阅读更多
文章标签: java lintcode
个人分类: java开发
想对作者说点什么? 我来说一句
相关热词

没有更多推荐了,返回首页

关闭
关闭
关闭