#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int n, ans, cnt[N], f[N << 1], a[N];
int c1[N], c2[N];
void solve1(int mx, int b) {
  int now = 0;
  memset(f, -1, sizeof(f));
  f[n] = 0;
  for (int i = 1; i <= n; i++) {
    if (a[i] == mx)
      now++;
    else if (a[i] == b)
      now--;
    if (f[n + now] > -1) ans = max(ans, i - f[n + now]);
    if (f[n + now] == -1) f[n + now] = i;
  }
}
void solve2(int lim) {
  int l = 1;
  memset(c1, 0, sizeof(c1));
  memset(c2, 0, sizeof(c2));
  for (int r = 1; r <= n; r++) {
    c2[c1[a[r]]]--;
    c2[++c1[a[r]]]++;
    while (c2[lim + 1]) {
      c2[c1[a[l]]]--;
      c2[--c1[a[l++]]]++;
    }
    if (c2[lim] > 1) ans = max(ans, r - l + 1);
  }
}
int main() {
  scanf("%d", &n);
  int mx = 0;
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
    ++cnt[a[i]];
  }
  for (int i = 1; i <= n; i++)
    if (cnt[i] > cnt[mx]) mx = i;
  int k = sqrt(n);
  for (int i = 1; i <= n; i++)
    if (i != mx && cnt[i] > k) solve1(mx, i);
  for (int lim = 1; lim <= k; lim++) solve2(lim);
  printf("%d", ans);
  return 0;
}
