题面大意
对于一个序列 将其分割出两个不重合的字段,使得在峰差不大于 的情况下,总长度最大。
我的思路:
发现解题难点在于 不重合 ,因此考虑分割端点,两侧用双指针维护,时间复杂度 。
更加优秀的解法
我的思路的要点在于二分的单调性,因为若左段的左端不变,左段越长,右段肯定不劣,所以考虑对从每一个节点能延伸的最长长度做记录,时间复杂度 。
AC代码:
#include<bits/stdc++.h>
using namespace std;
const int N=5e4+10;
int a[N],c[N],r=2,pre,ans;
int main()
{
ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
int n,k;
cin>>n>>k;
for(int i=1;i<=n;i++) cin>>a[i];
sort(a+1,a+n+1);
for(int i=1;i<=n;i++)
{
while(a[r]<=a[i]+k&&r<=n) r++;
c[r]=max(r-i,c[r]);
pre=max(pre,c[i]);
ans=max(ans,pre+r-i);
//if(r==n) break;
}
cout<<ans;
return 0;
}