#include <bits/stdc++.h>
using namespace std;
const int N = 200005, B = 205;
int n, t, id, rk[N], q[N], a[N];
int vis[N], ans, c[N];
vector<int> v[N];
void solve1(int id2) {
  for (int i = (int)(0); i <= (int)(n + 1); i++) vis[i] = -1;
  int S = t;
  vis[S] = 0;
  for (int i = (int)(1); i <= (int)(n); i++) {
    if (a[i] == id) ++S;
    if (a[i] == id2) --S;
    if (vis[S] != -1)
      ans = max(ans, i - vis[S]);
    else
      vis[S] = i;
  }
}
int su[N][B];
void solve2() {
  memset(su, 1, sizeof(su));
  for (int i = (int)(1); i <= (int)(n); i++)
    if (i != id & c[i] <= B)
      for (int j = (int)(0); j <= (int)(v[i].size() - 1); j++)
        for (int k = (int)(j); k <= (int)(v[i].size() - 1); k++)
          su[v[i][j]][k - j + 1] = min(su[v[i][j]][k - j + 1], v[i][k]);
  for (int i = (int)(n); i >= (int)(1); i--)
    for (int j = (int)(1); j <= (int)(B); j++)
      su[i][j] = min(su[i][j], su[i + 1][j]);
  for (int i = (int)(0); i <= (int)(t); i++)
    for (int j = (int)(1); j <= (int)(B); j++)
      if (i + j <= t)
        if (su[q[i] + 1][j] <= q[i + j + 1])
          ans = max(ans, q[i + j + 1] - q[i] - 1);
}
int main() {
  scanf("%d", &n);
  for (int i = (int)(1); i <= (int)(n); i++) scanf("%d", &a[i]);
  for (int i = (int)(1); i <= (int)(n); i++) ++c[a[i]];
  for (int i = (int)(1); i <= (int)(n); i++) v[a[i]].push_back(i);
  for (int i = (int)(1); i <= (int)(n); i++)
    if (c[i] > c[id]) id = i;
  for (int i = (int)(1); i <= (int)(n); i++)
    if (a[i] == id) q[++t] = i;
  q[t + 1] = n + 1;
  for (int i = (int)(1); i <= (int)(n); i++)
    if (i != id && c[i] == c[id]) return printf("%d\n", n), 0;
  for (int i = (int)(1); i <= (int)(n); i++) rk[i] = rk[i - 1] + (a[i] == id);
  for (int i = (int)(1); i <= (int)(n); i++)
    if (c[i] >= B && i != id) solve1(i);
  solve2();
  cout << ans << endl;
}
