将式子 |a_i - K| \le p 展开: K - p \le a_i \le K + p。题目要求求解当 K 任意时,属于 [K - p, K + p]a_i 的元素个数最多。

由于 a_i10^6 以内,我们可以用 cnt 数组统计每一个 a_i 的出现次数,再用前缀和处理以便快速查询区间内的元素个数。

最后枚举 K 求解答案即可,时间复杂度为 O(n + \max\limits_{i = 1}^{n} a_i)

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, p;
    cin >> n >> p;
    vector<int> a(n);
    int mx = 0;
    for(int i = 0;i < n;i++){
        cin >> a[i];
        mx = max(mx, a[i]);
    }
    vector<int> cnt(mx + 1, 0), pre(mx + 1, 0);
    for(int i = 0;i < n;i++)    cnt[a[i]]++;
    for(int i = 1;i <= mx;i++){
        pre[i] = pre[i - 1] + cnt[i];
    }
    int ans = 0;
    for(int K = 1;K <= mx;K++){
        int l = max(1, K - p);
        int r = min(mx, K + p);
        ans = max(ans, pre[r] - pre[l - 1]);
    }
    cout << ans << "\n";
}