【名词解释】
第一行输入两个整数
。
第二行输入
个整数
。
输出一个整数,表示满足条件的最多可选元素数量。
5 3 2 1 5 3 2
4
选取元素集合满足最大值与最小值之差为
,且无法再加入
。
import java.util.*;
import java.io.*;
//随机选择数组元素可不按顺序
//数组先排序,排序后根据k获取区间长度
//因为最长区间可能是中间区间,所以还要全部遍历。
//排序后滑动找最大满足条件的滑动窗口
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
String[] line1=bf.readLine().split(" ");
int n=Integer.parseInt(line1[0]);
int k=Integer.parseInt(line1[1]);
int[] ch=Arrays.stream(bf.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
Arrays.sort(ch);
int temp=0;//当前窗口
int maxLen=0;//最大窗口
//逐步滑动右侧,左侧按条件滑动
for(int l=0, i=1;i<ch.length;i++){
if(ch[i]-ch[l]<=k){
temp++;//满足条件后统计长度并右侧滑动
if(maxLen<temp){
maxLen=temp;
}
}else{
//不满足条件时左侧滑动,同步右侧滑动r++。
//此时窗口始终和上一次满足条件时窗口长度一致
l++;
}
}
System.out.println(maxLen+1);//没有输出为0的用例
// if(maxLen!=0){
// System.out.println(maxLen+1);
// }else{
// System.out.println(maxLen);
// }
}
} public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
Arrays.sort(arr);
int a = 0, b = 0;
int res = 1;
while (b < n) {
while (b < n && arr[b] - arr[a] <= k) b++;
res = Math.max(res, b - a);
if(b == n) break;
while (a<b && arr[b] - arr[a] > k) a++;
}
System.out.println(res);
} import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
int n = sc.nextInt();//输入整数个数
int k = sc.nextInt();//间隔k
ArrayList<Integer> list = new ArrayList<>();
for(int i=1;i<=n;i++){
list.add(sc.nextInt());
}
Collections.sort(list);//将输入的整数从小到大排序
int max = 0;
int len = list.size();
int start,end;
for(start=0,end=0;end<len;){
if(list.get(end)-list.get(start)<=k)
end++;
else{
max = max<end-start?end-start:max;
start++;
}
}
max = max<end-start?end-start:max;
System.out.println(max);
}
}