#include <bits/stdc++.h>   using namespace std;   const long long maxn = 2e6 + 100;   const long long inf = 0x3f3f3f3f;   const long long iinf = 1 << 30;   const long long linf = 2e18;   const long long mod = 998244353;   const double eps = 1e-7;   template <class T = long long>   T chmin(T &a, T b) {     return a = min(a, b);   }   template <class T = long long>   T chmax(T &a, T b) {     return a = max(a, b);   }   template <class T = long long>   inline void red(T &x) {     x -= mod, x += x >> 31 & mod;   }   template <class T = long long>   T read() {     T f = 1, a = 0;     char ch = getchar();     while (!isdigit(ch)) {       if (ch ==  - ) f = -1;       ch = getchar();     }     while (isdigit(ch)) {       a = (a << 3) + (a << 1) + ch -  0 ;       ch = getchar();     }     return a * f;   }   long long n, sqrt_n = 300;   long long ans, val;   long long a[maxn], cnt[maxn], sum[maxn], t[maxn], cnt1[maxn], cnt2[maxn];   vector<long long> pos;   void modify(long long x, long long pos) {     cnt2[cnt1[x]]--;     cnt1[x] += pos;     cnt2[cnt1[x]]++;   }   signed main() {     n = read();     for (long long i = (1); i <= (n); ++i) a[i] = read(), cnt[a[i]]++;     long long maxx = 0, tot = 0, val = 0;     for (long long i = (1); i <= (n); ++i) {       if (cnt[i] == maxx) tot++;       if (cnt[i] > maxx) tot = 1, maxx = cnt[i], val = i;     }     if (tot > 1) {       printf( %lld n , n);       return 0;     }     for (long long i = (1); i <= (n); ++i)       if (cnt[i] > sqrt_n && i != val) pos.push_back(i);     for (long long i : pos) {       for (long long j = (1); j <= (n); ++j)         sum[j] = sum[j - 1] + (a[j] == i ? -1 : (a[j] == val ? 1 : 0));       for (long long j = (-n); j <= (n); ++j) t[j + n] = linf;       t[n] = 0;       for (long long j = (1); j <= (n); ++j) {         if (t[sum[j] + n] != linf)           chmax(ans, j - t[sum[j] + n]);         else           t[sum[j] + n] = j;       }     }     for (long long i = (1); i <= (sqrt_n); ++i) {       for (long long j = (1); j <= (n); ++j) cnt1[j] = cnt2[j] = 0;       long long l = 1, r = 0;       while (r < n) {         modify(a[++r], 1);         while (cnt1[a[r]] > i) modify(a[l++], -1);         if (cnt2[i] >= 2) chmax(ans, r - l + 1);       }     }     printf( %lld n , ans);     return 0;   }   