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. Note The subarray should contain at least one number Example For [1, 2, -3, 1], return 6 Challenge O(n) time and O(n) space.
思路:把数组分成两部分,可以从i和i+1(0<= i < len-1)之间分开,a[0, i] a[i+1, len-1],然后分别求两个子数组中的最大子段和,以及最小字段和,然后求差的最大值即可。
1 public class Solution { 2 /** 3 * @param nums: A list of integers 4 * @return: An integer indicate the value of maximum difference between two 5 * Subarrays 6 */ 7 public int maxDiffSubArrays(ArrayList<Integer> nums) { 8 // write your code 9 if (nums==null || nums.size()==0) return 0; 10 int len = nums.size(); 11 int[] lGlobalMax = new int[len]; 12 int[] lGlobalMin = new int[len]; 13 int lLocalMax = nums.get(0); 14 int lLocalMin = nums.get(0); 15 lGlobalMax[0] = lLocalMax; 16 lGlobalMin[0] = lLocalMin; 17 for (int i=1; i<len; i++) { 18 lLocalMax = Math.max(lLocalMax+nums.get(i), nums.get(i)); 19 lGlobalMax[i] = Math.max(lLocalMax, lGlobalMax[i-1]); 20 21 lLocalMin = Math.min(lLocalMin+nums.get(i), nums.get(i)); 22 lGlobalMin[i] = Math.min(lLocalMin, lGlobalMin[i-1]); 23 } 24 25 int[] rGlobalMax = new int[len]; 26 int[] rGlobalMin = new int[len]; 27 int rLocalMax = nums.get(len-1); 28 int rLocalMin = nums.get(len-1); 29 rGlobalMax[len-1] = rLocalMax; 30 rGlobalMin[len-1] = rLocalMin; 31 for (int i=len-2; i>=0; i--) { 32 rLocalMax = Math.max(rLocalMax+nums.get(i), nums.get(i)); 33 rGlobalMax[i] = Math.max(rLocalMax, rGlobalMax[i+1]); 34 35 rLocalMin = Math.min(rLocalMin+nums.get(i), nums.get(i)); 36 rGlobalMin[i] = Math.min(rLocalMin, rGlobalMin[i+1]); 37 } 38 39 int maxDiff = Integer.MIN_VALUE; 40 for (int i=0; i<len-1; i++) { 41 if (maxDiff < Math.abs(lGlobalMax[i]-rGlobalMin[i+1])) 42 maxDiff = Math.abs(lGlobalMax[i]-rGlobalMin[i+1]); 43 44 45 if (maxDiff < Math.abs(lGlobalMin[i]-rGlobalMax[i+1])) 46 maxDiff = Math.abs(lGlobalMin[i]-rGlobalMax[i+1]); 47 } 48 return maxDiff; 49 } 50 }