#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 9;
const int L = 301;
const int INF = 1e9 + 239;
int n;
int a[N];
int cnt[N];
vector<int> pos[N];
int mn[2 * N];
void solve(vector<pair<int, int>> v, int &ans) {
  v.push_back({n - 1, 0});
  int c = 0;
  mn[N] = 0;
  for (auto [pos, val] : v) {
    ans = max(ans, (pos - 1) - mn[c + N] + 1);
    c += val;
    ans = max(ans, pos - mn[c + N] + 1);
    mn[c + N] = min(mn[c + N], pos + 1);
  }
  c = 0;
  mn[0] = INF;
  for (auto [pos, val] : v) {
    c += val;
    mn[c + N] = INF;
  }
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  fill(mn, mn + 2 * N, INF);
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    cnt[a[i]]++;
    pos[a[i]].push_back(i);
  }
  int ans = 0;
  int mx = max_element(cnt, cnt + N) - cnt;
  cerr << "mx " << mx << endl;
  auto relax_small = [&](int s) {
    if (pos[s].empty()) {
      return;
    }
    vector<pair<int, int>> vplus;
    vector<pair<int, int>> vminus;
    int sz = (int)pos[s].size();
    int pnt = -1;
    for (auto p : pos[s]) {
      int imx =
          lower_bound(pos[mx].begin(), pos[mx].end(), p) - pos[mx].begin();
      int l = max(pnt + 1, imx - (sz + 3));
      for (int i = l; i <= imx + (sz + 3) && i < (int)pos[mx].size(); i++) {
        vplus.push_back({pos[mx][i], 1});
        pnt = i;
      }
      vminus.push_back({p, -1});
    }
    vector<pair<int, int>> vall(vplus.size() + vminus.size());
    merge(vplus.begin(), vplus.end(), vminus.begin(), vminus.end(),
          vall.begin());
    solve(vall, ans);
  };
  auto relax_big = [&](int s) {
    if (pos[s].empty()) {
      return;
    }
    vector<pair<int, int>> vplus;
    vector<pair<int, int>> vminus;
    for (auto p : pos[mx]) {
      vplus.push_back({p, 1});
    }
    for (auto p : pos[s]) {
      vminus.push_back({p, -1});
    }
    vector<pair<int, int>> vall(vplus.size() + vminus.size());
    merge(vplus.begin(), vplus.end(), vminus.begin(), vminus.end(),
          vall.begin());
    solve(vall, ans);
  };
  for (int other = 0; other < N; other++) {
    if (other == mx) {
      continue;
    }
    relax_big(other);
  }
  cout << ans << '\n';
}
