#include <bits/stdc++.h>
using namespace std;
const int Maxn = 200010;
const int inf = 2147483647;
const double pi = acos(-1.0);
int read() {
  int x = 0, f = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar();
  return x * f;
}
int n, a[Maxn], pos[Maxn << 1], cnt[Maxn], cnt1[Maxn];
int main() {
  memset(pos, -1, sizeof(pos));
  n = read();
  for (int i = 1; i <= n; i++) cnt[a[i] = read()]++;
  int c = 0, mx = 0, num;
  for (int i = 1; i <= n; i++) {
    if (cnt[i] > mx)
      mx = cnt[i], c = 1, num = i;
    else if (cnt[i] == mx)
      c++;
  }
  if (mx == n) return puts("0"), 0;
  if (c > 1) return printf("%d", n), 0;
  int o = (int)sqrt(n), ans = 2;
  for (int i = 1; i <= n; i++)
    if (cnt[i] >= o && i != num) {
      int s = 0;
      pos[n] = 0;
      for (int j = 1; j <= n; j++) {
        int v;
        if (a[j] == num)
          v = 1;
        else if (a[j] == i)
          v = -1;
        else
          v = 0;
        s += v;
        if (pos[s + n] == -1)
          pos[s + n] = j;
        else
          ans = max(ans, j - pos[s + n]);
      }
      s = 0;
      for (int j = 1; j <= n; j++) {
        int v;
        if (a[j] == num)
          v = 1;
        else if (a[j] == i)
          v = -1;
        else
          v = 0;
        s += v;
        pos[s + n] = -1;
      }
    }
  for (int i = 1; i < o; i++) {
    int l = 1;
    mx = c = 0;
    for (int j = 1; j <= n; j++) cnt[j] = cnt1[j] = 0;
    cnt1[0] = n;
    for (int r = 1; r <= n; r++) {
      cnt1[cnt[a[r]]]--;
      cnt[a[r]]++;
      cnt1[cnt[a[r]]]++;
      if (cnt[a[r]] > mx)
        mx = cnt[a[r]], c = 1;
      else if (cnt[a[r]] == mx)
        c++;
      while (mx > i) {
        if (cnt[a[l]] == mx) {
          c--;
          if (!c) mx--, c = cnt1[mx] + 1;
        }
        cnt1[cnt[a[l]]]--;
        cnt[a[l]]--;
        cnt1[cnt[a[l]]]++;
        l++;
      }
      if (c > 1) ans = max(ans, r - l + 1);
    }
  }
  printf("%d", ans);
}
