#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const long long mod = 1e9 + 7;
const int N = 200005;
int a[N], b[N], data[N * 2], *d = data + 200000;
int c[N], e[N], mx;
void update(int x, int d) {
  e[c[x]]--;
  c[x] += d;
  e[c[x]]++;
  mx = max(mx, c[x]);
  while (e[mx] == 0) mx--;
}
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
    b[a[i]]++;
  }
  int wc = 0;
  for (int i = 1; i <= n; i++) {
    if (b[i] > b[wc]) wc = i;
  }
  for (int i = 1; i <= n; i++) {
    if (i != wc && b[i] == b[wc]) {
      return printf("%d\n", n), 0;
    }
  }
  int ans = 0;
  int tv = sqrt(n);
  for (int i = 1; i <= min(tv, b[wc]); i++) {
    for (int j = 1; j <= n; j++) c[j] = e[j] = 0;
    mx = 0;
    int cnt = 0;
    for (int j = 1, k = 0; j <= n; j++) {
      while (k + 1 <= n && cnt + (a[k + 1] == wc) <= i)
        k++, cnt += a[k + 1] == wc, update(a[k], 1);
      if (e[mx] >= 2) ans = max(ans, k - j + 1);
      update(a[j], -1), cnt -= a[j] == wc;
    }
  }
  for (int u = 1; u <= n; u++) {
    if (u == wc) continue;
    if (b[u] >= tv) {
      for (int i = -n; i <= n; i++) d[i] = -1;
      int now = 0;
      d[now] = 0;
      for (int i = 1; i <= n; i++) {
        if (a[i] == u) now++;
        if (a[i] == wc) now--;
        if (d[now] == -1) {
          d[now] = i;
        } else {
          ans = max(ans, i - d[now]);
        }
      }
    }
  }
  printf("%d\n", ans);
  return 0;
}
