题目:给定一个数组arr,其中有很多的子数组,找到两个不相容子数组使得相加的和最大,并返回和的最大值。
实现:
/*
* 最长的可整合子数组的长度
* 先给出可整合数组的定义。如果一个数组在排序之后,每相邻两个数差的绝对值都为1,则该数组为可整合数组。
* 例如,[5,3,4,6,2]排序之后为[2,3,4,5,6],符合每相邻两个数差的绝对值都为1,所以这个数组为可整合数组。
* 给定一个整型数组arr,请返回其中最大可整合子数组的长度。
* 例如,[5,5,3,2,6,4,3]中最大可整合子数组为[5,3,2,6,4],所以返回5。
*/
package org.com.niuke;
import java.util.*;
public class ArrayZhengHe {
public static int arrayZheng(int a[]) {
int len = 0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
HashSet<Integer> hash = new HashSet<Integer>();
for(int i = 0; i < a.length; i++) {
for(int j = i; j < a.length; j++) {
if(hash.contains(a[j])) {
break;
}
hash.add(a[j]);
if(min > a[j]) min = a[j];
if(max < a[j]) max = a[j];
if(max - min == j - i) {
len = Math.max(j - i + 1, len);
}
}
hash.clear();
max = Integer.MIN_VALUE;
min = Integer.MAX_VALUE;
}
return len;
}
public static void main(String args[]) {
int a[] = {3,3,2,1};
int result = arrayZheng(a);
System.out.println(result);
}
}