题目要求最大最小值差值要小于等于k,因此我们只需要考虑答案集合中最大的数和最小的数,处于中间的数不考虑。

那么为了获得最值,可以对数组进行排序,这样可以得到数的大小关系。

然后对于每一个数,我们只要找到a_i+k的位置,就能找到有多少个数,每个a_i求一个答案,最终求出最大值即可。

很自然地想到双指针,用左指针代表a_i,右指针去寻找 a_i+k

#include <iostream>
#include <algorithm>
#define int long long
using namespace std;
const int N = 1e6 + 5;
int a[N];
signed main() {
    int t;cin >> t;
    while(t--){
        int n,k;scanf("%lld%lld",&n,&k);
        for(int i=1;i<=n;i++) scanf("%lld",&a[i]);
        sort(a+1,a+1+n);
        int ans = 0;
        int l=1,r = 1;
        while(l <= n and r <= n){
            if(a[r] - a[l] <= k){
                ans = max(ans,r-l+1);
                r++;
            }
            else{
                l++;
            }
        }
        cout << ans << '\n';
    }
}