#include <bits/stdc++.h>
using namespace std;
int n, a[200010], occ[200010];
const int B = 300;
int sum[200010], miPos[200010 << 1];
const int off = 2e5;
int ans = 0;
int solve1(int mo1, int mo2) {
  int re = 0;
  memset(miPos, -1, sizeof(miPos));
  miPos[off] = 0;
  for (int i = 1; i <= n; i++) {
    sum[i] = (a[i] == mo1 ? 1 : a[i] == mo2 ? -1 : 0) + sum[i - 1];
    if (miPos[sum[i] + off] != -1) {
      re = max(re, i - miPos[sum[i] + off]);
    } else {
      miPos[sum[i] + off] = i;
    }
  }
  return re;
}
int t[200010], tot;
void solve2(int Times) {
  auto add = [&](int x, int y) {
    tot -= t[x] == Times;
    t[x] += y;
    tot += t[x] == Times;
  };
  tot = 0;
  memset(t, 0, sizeof(t));
  for (int r = 1, l = 1; r <= n; r++) {
    add(a[r], 1);
    while (t[a[r]] > Times) add(a[l++], -1);
    if (tot > 1) ans = max(ans, r - l + 1);
  }
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
    occ[a[i]]++;
  }
  if (occ[a[1]] == n) return printf("0"), 0;
  int mode = 1, p = 1;
  for (int i = 2; i <= n; i++) {
    if (occ[i] > occ[mode])
      mode = i, p = 1;
    else if (occ[i] == occ[mode])
      p++;
  }
  if (p > 1) return printf("%d\n", n), 0;
  for (int i = 1; i <= n; i++) {
    if (occ[i] > B && i != mode) {
      ans = max(ans, solve1(mode, i));
    }
  }
  for (int i = 1; i <= B; i++) solve2(i);
  printf("%d", ans);
}
