码迷,mamicode.com
首页 > 其他好文 > 详细

Eric Chen Mock Interview

时间:2016-06-27 06:53:01      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

 1 Given an array with integers.
 2 Find two non-overlapping subarrays A and B, which |SUM(A) - SUM(B)| is the largest.
 3 Return the largest difference.
 4 1,-2,3,-1
 5 1,3 A
 6 -1 B
 7 7
 8  
 9 public int maxDiffSubArrays(int[] nums) {
10 // write your code here
11  
12 }
13  
14 Solution: 
15  
16 public int maxDiffSubArrays(ArrayList<Integer> nums) {
17         // write your code
18         if (nums==null || nums.size()==0) return 0;
19         int len = nums.size();
20         int[] lGlobalMax = new int[len];
21         int[] lGlobalMin = new int[len];
22         int lLocalMax = nums.get(0);
23         int lLocalMin = nums.get(0);
24         lGlobalMax[0] = lLocalMax;
25         lGlobalMin[0] = lLocalMin;
26 for (int i=1; i<len; i++) { 27 lLocalMax = Math.max(lLocalMax+nums.get(i), nums.get(i)); 28 lGlobalMax[i] = Math.max(lLocalMax, lGlobalMax[i-1]); 29 lLocalMin = Math.min(lLocalMin+nums.get(i), nums.get(i)); 30 lGlobalMin[i] = Math.min(lLocalMin, lGlobalMin[i-1]); 31      } 32 int[] rGlobalMax = new int[len]; 33 int[] rGlobalMin = new int[len]; 34 int rLocalMax = nums.get(len-1); 35 int rLocalMin = nums.get(len-1); 36 rGlobalMax[len-1] = rLocalMax; 37 rGlobalMin[len-1] = rLocalMin;
38      for (int i=len-2; i>=0; i--) { 39 rLocalMax = Math.max(rLocalMax+nums.get(i), nums.get(i)); 40 rGlobalMax[i] = Math.max(rLocalMax, rGlobalMax[i+1]); 41 rLocalMin = Math.min(rLocalMin+nums.get(i), nums.get(i)); 42 rGlobalMin[i] = Math.min(rLocalMin, rGlobalMin[i+1]); 43 } 44 45 int maxDiff = Integer.MIN_VALUE;
46 for (int i=0; i<len-1; i++) { 47 if (maxDiff < Math.abs(lGlobalMax[i]-rGlobalMin[i+1])) 48 maxDiff = Math.abs(lGlobalMax[i]-rGlobalMin[i+1]); 49 50 if (maxDiff < Math.abs(lGlobalMin[i]-rGlobalMax[i+1])) 51 maxDiff = Math.abs(lGlobalMin[i]-rGlobalMax[i+1]); 52 }
53 return maxDiff; 54}

 

Eric Chen Mock Interview

标签:

原文地址:http://www.cnblogs.com/bambu/p/5619060.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!