#include <bits/stdc++.h>
using std::vector;
int n, a[200005], blc, cnt[200005 << 1], off = 200005, id[200005], x;
vector<int> v[200005], ta, tb;
inline int solve(vector<int> a, vector<int> b, int st, int ed) {
  int l = 0, r = 0, cur = 0, ret = 0;
  std::fill(cnt + off - a.size(), cnt + off, n + 1);
  std::fill(cnt + off, cnt + off + b.size() + 1, st);
  while (l < a.size() || r < b.size()) {
    if (r < b.size() && (l == a.size() || a[l] > b[r])) {
      ++cur;
      ++r;
    } else {
      ret = std::max(ret, a[l] - cnt[cur + off] - 1);
      --cur;
      (cnt[cur + off] > n ? cnt[cur + off] = a[l] : 0);
      ++l;
    }
  }
  ret = std::max(ret, ed - cnt[cur + off] - 1);
  return ret;
}
inline int solve1(const vector<int> &x, vector<int> a) {
  int ret = 0;
  for (int i = 0; i < a.size(); ++i) {
    ta.clear(), tb.clear();
    int l = id[a[i]] - 1, r = i, tot = 0;
    while (tot <= 3 * a.size() + 1 && (l >= 0 || r >= 0)) {
      if (r >= 0 && (l == -1 || x[l] < a[r]))
        tb.push_back(a[r]), --r;
      else
        ta.push_back(x[l]), --l;
      ++tot;
    }
    int st = (l == -1 ? 0 : x[l]);
    std::reverse(ta.begin(), ta.end());
    std::reverse(tb.begin(), tb.end());
    l = id[a[i]], r = i + 1, tot = 0;
    while (tot <= 3 * a.size() + 1 && (l < x.size() || r < a.size())) {
      if (r < a.size() && (l == x.size() || x[l] > a[r]))
        tb.push_back(a[r]), ++r;
      else
        ta.push_back(x[l]), ++l;
      ++tot;
    }
    ret = std::max(ret, solve(ta, tb, st, (l == x.size() ? n + 1 : x[l])));
  }
  return ret;
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) scanf("%d", a + i), v[a[i]].push_back(i);
  for (int i = 1; i <= n; ++i) ++cnt[a[i]];
  for (int i = 1; i <= n; ++i)
    if (cnt[i] > cnt[x]) x = i;
  std::fill(cnt + 1, cnt + n + 1, 0);
  for (int i = 1; i <= n; ++i)
    if (a[i] == x)
      id[i] = id[i - 1] + 1;
    else
      id[i] = id[i - 1];
  blc = sqrt(n) / 2;
  int ans = 0;
  for (int i = 1; i <= n; ++i)
    if (i != x && !v[i].empty()) {
      if (v[i].size() > blc)
        ans = std::max(ans, solve(v[x], v[i], 0, n + 1));
      else
        ans = std::max(ans, solve1(v[x], v[i]));
    }
  printf("%d\n", ans);
  return 0;
}
