P3143 [USACO16OPEN]Diamond Collector S
首先强行选择一个点
然后计算它左边最多长区间,右边也是
就可以了
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
int a[600001];
int n,k;
int l[600001];
int ans;
int main(){
scanf("%d%d",&n,&k);
for(int i=1;i<=n;++i){
scanf("%d",&a[i]);
}
sort(a+1,a+n+1);
a[n+1]=9999999999;
for(int i=1;i<=n;++i){
int ll=lower_bound(a+1,a+i+1,a[i]-k)-a;
l[i]=max(l[i-1],i-ll+1);
// cout<<l[i]<<endl;
}
for(int i=n-1;i>=1;--i){
int rr=upper_bound(a+1+i,a+n+1,a[i+1]+k)-a;
if(a[rr]>a[i+1]+k){
rr--;
}
ans=max(ans,l[i]+(rr-i));
}
cout<<ans;
return 0;
}