依旧是维护两个单调队列,只是队首检查的方式略有变动
1 /*by SilverN*/ 2 #include<iostream> 3 #include<algorithm> 4 #include<cstring> 5 #include<cstdio> 6 #include<cmath> 7 using namespace std; 8 const int mxn=3000200; 9 struct que{ 10 int v;//val 11 int p;//pos 12 }; 13 que mx[mxn],mi[mxn]; 14 int h1,h2,t1,t2; 15 int k,n; 16 int a[mxn]; 17 int ans=0; 18 int main(){ 19 scanf("%d%d",&k,&n); 20 int i,j; 21 for(i=1;i<=n;i++)scanf("%d",&a[i]); 22 h1=1;h2=1;t1=0;t2=0; 23 int le=0; 24 for(i=1;i<=n;i++){ 25 //max 26 while(h1<=t1 && a[i]>=mx[t1].v)t1--; 27 mx[++t1].v=a[i]; 28 mx[t1].p=i; 29 //min 30 while(h2<=t2 && a[i]<=mi[t2].v)t2--; 31 mi[++t2].v=a[i]; 32 mi[t2].p=i; 33 34 printf("test1 %d\n",mx[h1].v-mi[h2].v); 35 while(mx[h1].v-mi[h2].v>k){//若两队首元素差大于k,更新队头 36 le=min(mx[h1].p,mi[h2].p)+1; 37 while(le>mx[h1].p)h1++;//队首维护 38 while(le>mi[h2].p)h2++; 39 40 } 41 printf("test2 %d\n",mx[h1].v-mi[h2].v); 42 ans=max(ans,i-le+1); 43 } 44 printf("%d\n",ans-1); 45 return 0; 46 }