题解 | #相差不超过k的最多数#
相差不超过k的最多数
https://www.nowcoder.com/practice/562630ca90ac40ce89443c91060574c6
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
int n = in.nextInt();
long target = in.nextLong();
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextLong();
}
Arrays.sort(arr);
int res = 0;
int l = 0;
int r = 0;
//因为要遍历到最后一个所以条件r<n
while (r < n) {
if (arr[r] - arr[l] > target) {
l++;
}
//能够取值肯定在两棵指针之间,所以res的计算方法如下
res = Math.max(res, r - l + 1);
r++;
}
System.out.println(res);
}
}
查看19道真题和解析
文远知行公司福利 495人发布
