#include <bits/stdc++.h>
#pragma GCC optimize(2)
using namespace std;
const int inf = 0x3f3f3f3f;
const long long INF = 0x3f3f3f3f3f3f3f3fLL;
const double PI = acos(-1.0);
const long double eps = 1e-8;
const int mod = 998244353;
const int maxn = 2e5 + 100;
const int N = 2e5 + 100;
const int M = (1 << 20) + 10;
const long long mm = (1LL << 32);
template <class T>
inline void read(T &x) {
  x = 0;
  char c = getchar();
  bool f = 0;
  for (; !isdigit(c); c = getchar()) f ^= c == '-';
  for (; isdigit(c); c = getchar()) x = x * 10 + (c ^ 48);
  x = f ? -x : x;
}
template <class T>
inline void write(T x) {
  if (x < 0) {
    putchar('-');
    x = -x;
  }
  T y = 1;
  int len = 1;
  for (; y <= x / 10; y *= 10) ++len;
  for (; len; --len, x %= y, y /= 10) putchar(x / y + 48);
}
long long qpow(long long a, long long b, long long mod) {
  long long ans = 1;
  while (b) {
    if (b & 1) ans = (ans * a) % mod;
    b >>= 1;
    a = (a * a) % mod;
  }
  return ans;
}
int n, a[N], mx, pre[N << 1], sum[N << 1], num[N];
int calc(int x) {
  int ans = 0;
  for (int i = 0; i <= 2 * n; i++) pre[i] = 0;
  for (int i = 1; i <= n; i++) {
    sum[i] = sum[i - 1];
    if (a[i] == mx)
      sum[i]++;
    else if (a[i] == x)
      sum[i]--;
    if (sum[i] == 0)
      ans = max(i, ans);
    else {
      if (!pre[sum[i] + n])
        pre[sum[i] + n] = i;
      else
        ans = max(ans, i - pre[sum[i] + n]);
    }
  }
  return ans;
}
int CNT[N << 1], cnt[N << 1];
void add(int x) {
  --CNT[cnt[x]];
  ++CNT[++cnt[x]];
}
void del(int x) {
  --CNT[cnt[x]];
  ++CNT[--cnt[x]];
}
int calc2(int x) {
  for (int i = 1; i <= n; i++) CNT[i] = cnt[i] = 0;
  CNT[0] = n;
  int l = 1, tot = 0, ans = 0;
  for (int r = 1; r <= n; r++) {
    add(a[r]);
    if (a[r] == mx) tot++;
    if (tot < x)
      continue;
    else if (tot == x) {
      if (CNT[x] > 1) ans = max(ans, r - l + 1);
    } else {
      while (tot > x) {
        if (a[l] == mx) tot--;
        del(a[l++]);
      }
    }
  }
  return ans;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  int pos;
  for (int i = 1; i <= n; ++i) cin >> a[i], num[a[i]]++;
  for (int i = 1; i <= n; ++i) {
    if (mx < num[i]) mx = num[i], pos = i;
  }
  mx = pos;
  int ans = 0;
  int block = 500;
  for (int i = 1; i < block; i++) {
    ans = max(ans, calc2(i));
  }
  for (int i = 1; i <= n; i++) {
    if (i == mx) continue;
    if (num[i] >= block) ans = max(ans, calc(i));
  }
  cout << ans << "\n";
  return 0;
}
