1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| #include <bits/stdc++.h> #define fo(a,b,c) for (a=b; a<=c; a++) #define fd(a,b,c) for (a=b; a>=c; a--) #define max(a,b) (a>b?a:b) #define min(a,b) (a<b?a:b) #define ll long long
using namespace std;
int Sum[200002],sum[200002],a[200002],L[200002],R[200002],n,i,j,k,l,mx,mx2,ans; int ls[200002],d[800001][2],b[200002],c[200002],f[800001],I[200002],id[200002];
int get(int t,int x) { if (f[t]<=0) return -f[t]; return I[f[t]+(x-d[t][0])]; }
void work(int i,int s) { int j,k,l; l=sum[i]-sum[ls[s]]; while (l && b[s]<=R[s]) { k=get(b[s],c[s]),ans=max(ans,(I[id[s]+1]-1)-k); if (c[s]==d[b[s]][1]) ++b[s]; --l,++c[s],++id[s]; } if (b[s]>R[s]) ++R[s],d[R[s]][0]=d[R[s]-1][1]+1,d[R[s]][1]=c[s]+l,f[R[s]]=id[s],id[s]+=l,c[s]+=l;
k=get(b[s],c[s]),ans=max(ans,(i-1)-k);
if (i<=n) { if (c[s]==d[b[s]][0]) { if (b[s]==L[s]) { --L[s]; d[L[s]][0]=d[L[s]][1]=d[L[s]+1][0]-1; f[L[s]]=-i; } --b[s]; } --c[s]; } ls[s]=i; }
int main() { #ifdef file freopen("CF1446D.in","r",stdin);
#endif
scanf("%d",&n); fo(i,1,n) { scanf("%d",&a[i]),++Sum[a[i]]; if (Sum[a[i]]>mx) mx=Sum[a[i]],mx2=a[i]; } fo(i,1,n+1) sum[i]=sum[i-1]+(a[i]==mx2);
k=l=0; fo(i,1,n) if (i!=mx2) b[i]=l+(Sum[i]+1),L[i]=R[i]=b[i],c[i]=0,d[b[i]][0]=d[b[i]][1]=0,l+=Sum[i]*2+2; fo(i,1,n) if (a[i]==mx2) I[++k]=i;
fo(i,1,n) if (a[i]!=mx2) work(i,a[i]); fo(i,1,n) if (i!=mx2) work(n+1,i); printf("%d\n",ans);
fclose(stdin); fclose(stdout); return 0; }
|