#include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int rt = 500, mx, n;
int cnt[2 * 200005], arr[200005];
int cntwt[200005];
vector<int> adj[200005];
void add(int x) {
  cntwt[cnt[x]]--;
  cnt[x]++;
  cntwt[cnt[x]]++;
}
void remove(int x) {
  cntwt[cnt[x]]--;
  cnt[x]--;
  cntwt[cnt[x]]++;
}
int chk(int x) {
  int ret = 0;
  for (int i = 0; i <= 2 * n; i++) cnt[i] = -1;
  int cur = 0;
  cnt[cur + n] = 0;
  for (int i = 1; i <= n; i++) {
    if (arr[i] == x)
      cur++;
    else if (arr[i] == mx)
      cur--;
    if (cnt[cur + n] == -1)
      cnt[cur + n] = i;
    else
      ret = max(ret, i - cnt[cur + n]);
  }
  return ret;
}
void solve() {
  int i, j, k, l, r, m, a, b, c, d, x, y, z, t, p;
  scanf("%d", &n);
  for (i = 1; i <= n; i++) {
    scanf("%d", &arr[i]);
    cnt[arr[i]]++;
    adj[arr[i]].emplace_back(i);
  }
  x = 0;
  for (i = 1; i <= n; i++) {
    if (cnt[i] > cnt[mx]) {
      mx = i;
      x = 1;
    } else if (cnt[i] == cnt[mx]) {
      x++;
    }
  }
  if (x > 1) {
    printf("%d\n", n);
    return;
  }
  if (cnt[mx] == n) {
    printf("%d\n", 0);
    return;
  }
  adj[mx].push_back(n + 1);
  reverse(adj[mx].begin(), adj[mx].end());
  adj[mx].push_back(0);
  reverse(adj[mx].begin(), adj[mx].end());
  int ans = 0;
  for (i = 1; i <= n; i++) {
    if (adj[i].size() >= rt) {
      if (i != mx) ans = max(ans, chk(i));
    }
  }
  y = adj[mx].size();
  for (i = 2; i <= rt + 10; i++) {
    if (i >= adj[mx].size()) break;
    l = 1, r = 0;
    for (j = 0; j <= n; j++) {
      cntwt[j] = cnt[j] = 0;
    }
    cntwt[0] = n;
    for (j = i; j < adj[mx].size(); j++) {
      while (r < adj[mx][j] - 1) add(arr[++r]);
      while (l <= adj[mx][j - i]) remove(arr[l++]);
      if (cntwt[cnt[mx]] >= 2) {
        ans = max(ans, r - l + 1);
      }
      assert(l <= n + 1);
      assert(r <= n + 1);
    }
  }
  printf("%d\n", ans);
}
int32_t main() {
  int t = 1;
  while (t--) solve();
  return 0;
}
