#include <bits/stdc++.h>
using namespace std;
const int maxn = 4e5 + 5;
int n;
int sum[maxn], A[maxn], last[maxn];
int mx, cntmx, ans;
int num[maxn], cnt[maxn];
int read() {
  int x = 0, fl = 1;
  char ch = getchar();
  while ((ch < '0' || ch > '9') && ch != '-') ch = getchar();
  if (ch == '-') fl = -1, ch = getchar();
  while (ch >= '0' && ch <= '9')
    x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
  return x * fl;
}
void work(int x) {
  int res = n;
  for (int i = 1; i <= (n << 1); ++i) last[i] = n + 1;
  last[n] = 0;
  for (int i = 1; i <= n; ++i) {
    if (A[i] == mx) ++res;
    if (A[i] == x) --res;
    last[res] = min(last[res], i);
    ans = max(ans, i - last[res]);
  }
}
void rem(int x) { --cnt[num[x]], --num[x], ++cnt[num[x]]; }
void add(int x) { --cnt[num[x]], ++num[x], ++cnt[num[x]]; }
void calc(int x) {
  int pl = 0;
  for (int i = 1; i <= n; ++i) num[i] = cnt[i] = 0;
  for (int i = 1; i <= n; ++i) {
    if (num[A[i]] == x) {
      while (pl < i) {
        ++pl;
        rem(A[pl]);
        if (A[pl] == A[i]) break;
      }
    }
    add(A[i]);
    if (cnt[x] >= 2) ans = max(ans, i - pl);
  }
}
int main() {
  n = read();
  for (int i = 1; i <= n; ++i) A[i] = read(), ++sum[A[i]];
  for (int i = 1; i <= n; ++i) {
    if (sum[mx] < sum[i])
      mx = i, cntmx = 0;
    else if (sum[mx] == sum[i])
      ++cntmx;
  }
  if (cntmx >= 2)
    printf("%d", n);
  else {
    for (int i = 1; i <= n; ++i) {
      if (sum[i] && sum[i] >= n / sum[i] && i != mx) {
        work(i);
      }
    }
    for (int i = 1; i * i <= n; ++i) {
      calc(i);
    }
    printf("%d", ans);
  }
  return 0;
}
