我正在尝试以这样的方式解决数组中的配对数字(a,b)a*2 >=b。其中 a 和 b 是输入数组中的数字。
例子:
输入:a[] = {1,2,3,4,5}
输出:2
解释:
我们可以将 1 与 3 配对
2 与 4 或 5
输入:a[] = {4,3,2,1,5}
输出:2
解释:
我们可以将 1 与 3 配对
2 与 4 或 5
输入:a[] = {4,3,2,1,5,6}
输出:3
解释:
我们可以将 5 与 1 配对
2 与 4
3 与 6
我尝试使用如下递归来解决问题,但这并没有给出任何正确的结果。任何帮助,将不胜感激。
对输入数组进行排序
如果a[start] * 2 >= [end] found then add 1to result recur for start +1andend - 1
else为(start + 1, end),(start, end - 1)和 (start + 1, end - 1)
a[start]想法与数组中的剩余元素匹配并获得最大结果。
public static int countPairs(int[] a){
Arrays.sort(a);
return countPairs(a,a.length,0,a.length-1);
}
public static int countPairs(int[] a, int n, int start, int end){
if(end == start){
return 0;
}
if(start >= n || end < 0){
return 0;
}
System.out.print("matching start: "+start + " and end "+end+" ");System.out.println("matching "+a[start] + " and "+a[end]);
if(a[start] < a[end] && a[start] * 2 >= a[end] ){
int res = countPairs(a,n,start+1,end-1) +1;
//System.out.print("inside if matching start: "+start + " and end "+end+" ");System.out.println("matching "+a[start] + " and "+a[end] + " count is "+res);
return res;
}
else{
return max(countPairs(a,n,start+1,end) ,
countPairs(a,n,start,end - 1),countPairs(a,n,start+1,end - 1));
}
}
千巷猫影
HUX布斯
相关分类