Lintcode: Maximum Subarray Difference

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 }

 

转载于:https://www.cnblogs.com/EdwardLiu/p/4336961.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值