#include <bits/stdc++.h>
const int inf = 0x3f3f3f3f;
using namespace std;
int yh() {
  int ret = 0;
  bool f = 0;
  char c = getchar();
  while (!isdigit(c)) {
    if (c == EOF) return -1;
    if (c == '-') f = 1;
    c = getchar();
  }
  while (isdigit(c)) ret = (ret << 3) + (ret << 1) + (c ^ 48), c = getchar();
  return f ? -ret : ret;
}
template <typename T>
void yh(T& ret) {
  ret = 0;
  bool f = 0;
  char c = getchar();
  while (!isdigit(c)) {
    if (c == EOF) return ret = -1, void();
    if (c == '-') f = 1;
    c = getchar();
  }
  while (isdigit(c)) ret = (ret << 3) + (ret << 1) + (c ^ 48), c = getchar();
  ret = f ? -ret : ret;
}
const int maxn = 4e5 + 5;
int BOUND = 447;
int n;
int a[maxn], b[maxn], mp[maxn];
int pos[maxn];
int tot[maxn];
vector<int> most;
int cnt[maxn];
void ins(int x, int i) {
  if (pos[x + n] == inf) pos[x + n] = i;
}
int ask(int x) { return pos[x + n]; }
int main() {
  n = yh();
  int maxa = 0;
  for (register int i = (1); i <= (n); i++) {
    a[i] = yh();
    maxa = max(maxa, a[i]);
    tot[a[i]]++;
  }
  most.push_back(0);
  for (register int i = (1); i <= (maxa); i++) {
    if (tot[i] > tot[most[0]]) {
      most.clear();
      most.push_back(i);
    } else if (tot[i] == tot[most[0]]) {
      most.push_back(i);
    }
  }
  int ans = 0;
  int x = most[0];
  for (register int y = (1); y <= (maxa); y++)
    if (tot[y] > BOUND && y != x) {
      for (register int i = (0); i <= ((n << 1)); i++) pos[i] = inf;
      ins(0, 0);
      int s = 0;
      for (register int i = (1); i <= (n); i++) {
        if (a[i] == x)
          b[i] = 1;
        else if (a[i] == y)
          b[i] = -1;
        else
          b[i] = 0;
        s += b[i];
        ans = max(ans, i - ask(s));
        ins(s, i);
      }
    }
  cerr << ans << '\n';
  for (register int freq = (1); freq <= (BOUND); freq++) {
    int l = 1, r;
    for (register int i = (1); i <= (maxa); i++) cnt[i] = 0;
    for (register int i = (1); i <= (n); i++) mp[i] = 0;
    for (r = 1; r <= n; r++) {
      mp[cnt[a[r]]]--;
      mp[++cnt[a[r]]]++;
      while (cnt[a[r]] > freq) {
        mp[cnt[a[l]]]--;
        mp[--cnt[a[l]]]++;
        l++;
      }
      if (mp[freq] > 1) ans = max(ans, r - l + 1);
    }
  }
  cout << ans << '\n';
  return 0;
}
