#include <bits/stdc++.h>
using namespace std;
const int N = 200005;
int n, a[N], cnt[N], sum[N];
vector<int> pos[N];
set<int> S;
int main() {
  scanf("%d", &n);
  for (int i = (1); i <= (n); ++i)
    scanf("%d", &a[i]), ++cnt[a[i]], pos[a[i]].push_back(i);
  int tt = 0, mx = 0;
  for (int i = (1); i <= (n); ++i) {
    if (cnt[i] > cnt[mx]) {
      mx = i;
      tt = 0;
    }
    if (cnt[i] == cnt[mx]) {
      ++tt;
    }
  }
  if (tt > 1) {
    printf("%d\n", n);
    return 0;
  }
  for (int i = (1); i <= (n + 1); ++i)
    sum[i] = sum[i - 1] + (a[i] == mx), a[i] == mx && (S.insert(i), 0);
  int ans = 0;
  for (int i = (1); i <= (n); ++i)
    if (i != mx && ((int)(pos[i]).size())) {
      vector<int> v;
      for (auto x : pos[i]) {
        {
          auto it = S.lower_bound(x);
          if (it != S.begin()) {
            v.push_back(*prev(it));
            S.erase(prev(it));
          }
          if (it != S.end()) {
            v.push_back(*it);
            S.erase(*it);
          }
        }
        {
          auto it = S.lower_bound(x);
          if (it != S.begin()) {
            v.push_back(*prev(it));
            S.erase(prev(it));
          }
          if (it != S.end()) {
            v.push_back(*it);
            S.erase(*it);
          }
        }
      }
      vector<int> t(v);
      for (auto x : pos[i]) v.push_back(x);
      {
        auto it = S.lower_bound(*min_element(v.begin(), v.end()));
        if (it != S.begin()) {
          --it;
          v.push_back(*it);
        }
        v.push_back(0);
        it = S.upper_bound(*max_element(v.begin(), v.end()));
        if (it != S.end()) {
          v.push_back(*it);
        }
        v.push_back(n + 1);
      }
      sort(v.begin(), v.end());
      map<int, int> fi;
      fi[sum[v[0]]] = v[0];
      int s = 0;
      for (int j = (1); j <= (((int)(v).size()) - 1); ++j) {
        if (fi.count(sum[v[j] - 1] + s)) {
          ans = max(ans, v[j] - 1 - fi[sum[v[j] - 1] + s]);
        }
        if (a[v[j]] == i) --s;
        if (!fi.count(sum[v[j]] + s)) fi[sum[v[j]] + s] = v[j];
      }
      for (auto x : t) S.insert(x);
    }
  printf("%d\n", ans);
  return 0;
}
