#include <bits/stdc++.h>
using namespace std;
const int N = 4E5 + 5;
int cnt[N], ans, cnn[N], max1, n, a[N], b[N], zs, sum, vis[N];
int worka(int x) {
  for (int i = 0; i <= 2 * n; i++) cnt[i] = -1;
  cnt[n] = 0;
  int now = n;
  for (int i = 1; i <= n; i++) {
    if (a[i] == x) now++;
    if (a[i] == zs) now--;
    if (cnt[now] == -1) cnt[now] = i;
    ans = max(ans, i - cnt[now]);
  }
}
void add(int x) {
  cnn[cnt[x]]--;
  cnt[x]++;
  cnn[cnt[x]]++;
  max1 = max(max1, cnt[x]);
  sum += (x == zs);
}
void del(int x) {
  cnn[cnt[x]]--;
  cnt[x]--;
  cnn[cnt[x]]++;
  if (cnn[max1] == 0) max1 = cnt[x];
  sum -= (x == zs);
}
void workb(int k) {
  cnn[0] = n;
  for (int i = 1; i <= 2 * n; i++) cnt[i] = cnn[i] = 0;
  int l = 1, r = 0;
  max1 = 0;
  sum = 0;
  for (; l <= n;) {
    while (r < n && sum + (a[r + 1] == zs) <= k) add(a[r + 1]), r++;
    if (cnn[max1] >= 2) ans = max(ans, r - l + 1);
    del(a[l]);
    l++;
  }
}
int main() {
  scanf("%d", &n);
  int S = sqrt(n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
    b[a[i]]++;
    if (b[a[i]] > b[zs]) zs = a[i];
  }
  for (int i = 1; i <= n; i++) {
    if (vis[a[i]]) continue;
    if (a[i] != zs && b[a[i]] >= S) {
      worka(a[i]);
      vis[a[i]] = 1;
    }
  }
  for (int i = 1; i < S; i++) workb(i);
  printf("%d", ans);
}
