描述
给定一个整数数组,找出两个不重叠的子数组A和B,使两个子数组和的差的绝对值|SUM(A) - SUM(B)|最大。
返回这个最大的差值。
子数组最少包含一个数
样例
给出数组[1, 2, -3, 1],返回 6
挑战
时间复杂度为O(n),空间复杂度为O(n)
思路:因为两个子数组是不重叠的,所以肯定有一个分界线。首先从左往右遍历,第一次我们在左边的子数组中求得最大组数组,在右边的子数组求得最小子数组。然后求得他们得差值的绝对值的最大值。
第二次我们在左边的部分求最小子数组,在右边求最大子数组。
Java实现代码:
public static int majorityNumber(List<Integer> nums) {
// write your code here
int candidate1 = nums.get(0); int count1 = 0;
int candidate2 = nums.get(0); int count2 = 0;
int i = 0;
for (; i<nums.size() ; i++) {
if(nums.get(i)==candidate1){
count1++;
}else{
candidate2 = nums.get(i);
count2 = 1;
break;
}
}
for (; i<nums.size();i++) {
int temp = nums.get(i);
if(temp==candidate1){
count1++;
}else if(temp==candidate2){
count2++;
}else if(count1 == 0){
candidate1 = temp;
count1 = 1;
}else if(count2 == 0){
candidate2 = temp;
count2 = 1;
} else{
count1--;
count2--;
}
}
// 验证candidate1,2
int len = nums.size()/3+1;
int count = 0;
for (int n: nums) {
if(n==candidate1){
count++;
}
}
if(count>=len){
return candidate1;
}else{
return candidate2;
}
}