#include <bits/stdc++.h>
using namespace std;
std::mt19937 rnd(
    (int)std::chrono::steady_clock::now().time_since_epoch().count());
long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); }
const int MAXN = 200000;
int n;
int a[MAXN];
int cnt[MAXN], freq[MAXN + 1], mxcnt;
int solve() {
  int ret = 0;
  int magic = sqrt(n);
  for (int lim = (1); lim <= (magic); ++lim) {
    for (int i = (0); i < (n); ++i) cnt[i] = 0;
    for (int i = (0); i <= (n); ++i) freq[i] = 0;
    freq[0] = n, mxcnt = 0;
    int l = 0, r = 0;
    int cur = 0;
    while (true) {
      if (mxcnt > lim) {
        --freq[cnt[a[l]]];
        --cnt[a[l]];
        ++freq[cnt[a[l]]];
        ++l;
        if (freq[mxcnt] == 0) --mxcnt;
      } else {
        if (freq[mxcnt] >= 2) cur = max(cur, r - l);
        if (r >= n) break;
        --freq[cnt[a[r]]];
        ++cnt[a[r]];
        ++freq[cnt[a[r]]];
        ++r;
        if (mxcnt < n && freq[mxcnt + 1] > 0) ++mxcnt;
      }
    }
    ret = max(ret, cur);
  }
  for (int i = (0); i < (n); ++i) cnt[i] = 0;
  for (int i = (0); i < (n); ++i) ++cnt[a[i]];
  int x = 0;
  for (int i = (0); i < (n); ++i)
    if (cnt[i] > cnt[x]) x = i;
  for (int y = (0); y < (n); ++y)
    if (y != x && cnt[y] > magic) {
      vector<int> bal(n + 1);
      bal[0] = 0;
      for (int i = (0); i < (n); ++i)
        bal[i + 1] = bal[i] + (a[i] == x ? -1 : a[i] == y ? +1 : 0);
      int lo = 0;
      for (int i = (0); i <= (n); ++i) lo = min(lo, bal[i]);
      int hi = 0;
      for (int i = (0); i <= (n); ++i) hi = max(hi, bal[i]);
      vector<int> fst(hi - lo + 1, INT_MAX), lst(hi - lo + 1, INT_MIN);
      for (int i = (0); i <= (n); ++i)
        fst[bal[i] - lo] = min(fst[bal[i] - lo], i),
                     lst[bal[i] - lo] = max(lst[bal[i] - lo], i);
      int cur = 0;
      for (int i = (0); i < (((int)(fst).size())); ++i)
        if (fst[i] <= lst[i]) cur = max(cur, lst[i] - fst[i]);
      ret = max(ret, cur);
    }
  return ret;
}
void run() {
  scanf("%d", &n);
  for (int i = (0); i < (n); ++i) scanf("%d", &a[i]), --a[i];
  printf("%d\n", solve());
}
int solvestupid() {
  int ret = 0;
  for (int l = (0); l < (n); ++l) {
    vector<int> cnt(n, 0);
    vector<int> freq(n + 1, 0);
    freq[0] = n;
    int mxcnt = 0;
    for (int r = (l); r < (n); ++r) {
      --freq[cnt[a[r]]];
      ++cnt[a[r]];
      ++freq[cnt[a[r]]];
      if (mxcnt + 1 <= n && freq[mxcnt + 1] > 0) ++mxcnt;
      if (freq[mxcnt] >= 2) ret = max(ret, r - l + 1);
    }
  }
  return ret;
}
void stress() {
  for (int rep = (0); rep < (100000); ++rep) {
    n = rnd() % 1000 + 1;
    int mxval = rnd() % min(n, 100);
    for (int i = (0); i < (n); ++i) a[i] = rnd() % (mxval + 1);
    int have = solve();
    int want = solvestupid();
    if (have == want) {
      printf(".");
      continue;
    }
    printf("err have=%d want=%d\n", have, want);
  }
}
int main() {
  run();
  return 0;
}
