#include <bits/stdc++.h>
using namespace std;
const int MAXN = 200005;
const int B = 0;
int n, a[MAXN], p[2 * MAXN];
vector<int> c[MAXN], d;
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
    c[a[i]].push_back(i);
  }
  int g = 0;
  for (int i = 1; i <= n; i++)
    if (c[i].size() > c[g].size()) g = i;
  int ans = 0;
  for (int i = 0; i <= 2 * n; i++) p[i] = -1;
  for (int k = 1; k <= n; k++)
    if (k != g) {
      if (c[k].size() > B) {
        p[n] = 0;
        for (int i = 1, s = n; i <= n; i++) {
          if (a[i] == g)
            s++;
          else if (a[i] == k)
            s--;
          if (~p[s])
            ans = max(ans, i - p[s]);
          else
            p[s] = i;
        }
        for (int i = 0; i <= 2 * n; i++) p[i] = -1;
      } else {
        int cnt = c[k].size();
        for (int l = 0; l < cnt; l++) {
          int t = lower_bound(c[g].begin(), c[g].end(), c[k][l]) - c[g].begin();
          int j = max(t - cnt, 0), s = n;
          p[n] = j ? c[g][j - 1] : 0;
          for (int i = l; i < cnt; i++) {
            while (j < c[g].size() && j <= t + cnt && c[g][j] < c[k][i]) {
              s++;
              if (~p[s])
                ans =
                    max(ans, min((i + 1 < c[k].size() ? c[k][i + 1] - 1 : n),
                                 (j + 1 < c[g].size() ? c[g][j + 1] - 1 : n)) -
                                 p[s]);
              else
                p[s] = c[g][j], d.push_back(s);
              j++;
            }
            s--;
            if (~p[s])
              ans = max(ans, c[k][i] - p[s]);
            else
              p[s] = c[k][i], d.push_back(s);
          }
          while (j < c[g].size() && j <= t + cnt) {
            s++;
            if (~p[s])
              ans =
                  max(ans, (j + 1 < c[g].size() ? c[g][j + 1] - 1 : n) - p[s]);
            else
              p[s] = c[g][j], d.push_back(s);
            j++;
          }
          for (int i : d) p[i] = -1;
          d.clear();
        }
      }
    }
  printf("%d\n", ans);
  return 0;
}
