#include <bits/stdc++.h>
#pragma GCC optimize(2)
int n, a[400005], cn[400005], c[400005], c0[400005], ans, maxn, p[800005], mx,
    b[200005];
void ins(int x) {
  --c0[c[x]];
  ++c[x];
  ++c0[c[x]];
  if (c[x] > maxn) maxn = c[x];
}
void del(int x) {
  --c0[c[x]];
  --c[x];
  ++c0[c[x]];
  maxn -= (c0[maxn] == 0);
}
inline int solve(int v) {
  int ans = 0;
  memset(p, -1, sizeof p);
  int *w = p + 400000;
  for (int i = 1; i <= n; ++i)
    if (a[i] == mx)
      b[i] = 1;
    else if (a[i] == v)
      b[i] = -1;
    else
      b[i] = 0;
  for (int i = 1; i <= n; ++i) b[i] += b[i - 1];
  for (int i = 0; i <= n; ++i)
    if (w[b[i]] != -1) {
      int vw = w[b[i]];
      if (i - vw > ans) ans = i - vw;
    } else
      w[b[i]] = i;
  return ans;
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
    ++cn[a[i]];
    if (cn[a[i]] > cn[mx]) mx = a[i];
  }
  if (cn[mx] == n) return (printf("0"), 0);
  for (int i = 1; i <= n; i++)
    if (cn[i] >= 512 && i != mx) {
      int q = solve(i);
      if (q > ans) ans = q;
    }
  for (int i = 1; i <= 512; i++) {
    memset(c, 0, sizeof c);
    memset(c0, 0, sizeof c0);
    maxn = 0;
    c0[0] = n;
    for (int j = 1, k = 1, x = 0; j <= n; j++) {
      while (k <= n && x + (a[k] == mx) <= i) {
        ins(a[k]);
        x += (a[k] == mx);
        ++k;
      }
      if (c0[maxn] >= 2) {
        if (k - j > ans) ans = k - j;
      }
      del(a[j]);
      x -= a[j] == mx;
    }
  }
  printf("%d", ans);
  return 0;
}
