#include <bits/stdc++.h>
using namespace std;
int v[200002], fv[200002], p, sol, minpoz[400005], n, d[200002], poz[200002], k;
vector<int> a[200002];
inline void rez1(int x) {
  int i, s = 0;
  for (i = 1; i <= n; i++) {
    if (v[i] == p) s++;
    if (v[i] == x) s--;
    if (s == 0) sol = max(sol, i);
    if (minpoz[s + n] != 0)
      sol = max(sol, i - minpoz[s + n]);
    else
      minpoz[s + n] = i;
  }
  s = 0;
  for (i = 1; i <= n; i++) {
    if (v[i] == p) s++;
    if (v[i] == x) s--;
    minpoz[s + n] = 0;
  }
}
inline void rez2(int x) {
  int i, l, m = fv[x], t, tt, left, right, st, dr, j;
  for (l = m; l >= 1; l--) {
    for (i = 1; i <= m - l + 1; i++)
      if (a[x][i + l] - a[x][i - 1] - 1 > sol) {
        t = d[a[x][i + l - 1]] - d[a[x][i]];
        tt = d[a[x][i + l]] - d[a[x][i - 1]];
        left = a[x][i - 1] + 1;
        right = a[x][i + l] - 1;
        st = d[a[x][i]] + 1;
        dr = d[a[x][i + l - 1]];
        if (l >= t && l <= tt) {
          t = l - t;
          for (j = 0; j <= t; j++)
            if (st - j >= 1 && dr + t - j <= k && poz[st - j] >= left &&
                poz[dr + t - j] <= right)
              sol = max(sol, min(right, poz[dr + t - j + 1] - 1) -
                                 max(left, poz[st - j - 1] + 1) + 1);
        }
      }
  }
}
int main() {
  int i, maxim = 0, r;
  cin >> n;
  for (i = 1; i <= n; i++) {
    cin >> v[i];
    fv[v[i]]++;
    if (a[v[i]].empty()) a[v[i]].push_back(0);
    a[v[i]].push_back(i);
    if (fv[v[i]] > maxim)
      maxim = fv[v[i]], p = v[i];
    else if (fv[v[i]] == maxim)
      p = 0;
  }
  for (i = 1; i <= n; i++)
    if (a[v[i]][a[v[i]].size() - 1] != n + 1) a[v[i]].push_back(n + 1);
  if (p == 0)
    cout << n;
  else {
    for (i = 1; i <= n; i++) {
      d[i] = d[i - 1];
      if (v[i] == p) {
        d[i]++;
        poz[++k] = i;
      }
    }
    d[n + 1] = d[n];
    poz[k + 1] = n + 1;
    r = sqrtl(n);
    for (i = 1; i <= n; i++)
      if (fv[i] > 0 && i != p) {
        if (fv[i] >= r)
          rez1(i);
        else
          rez2(i);
      }
    cout << sol;
  }
  return 0;
}
