#include <bits/stdc++.h>
using namespace std;
int n, cnt[200200], mx = 0, val = 0, arr[200200], pr[200200], a[200200], ans;
vector<int> lst, bd;
void tryBuild(int i) {
  vector<int> lPos(400400, -1);
  lPos[200000] = 0;
  for (int i1 = 1; i1 <= n; i1++) {
    if (a[i1] == i) {
      arr[i1] = 1;
    } else {
      if (a[i1] != val) {
        arr[i1] = 0;
      }
    }
    pr[i1] = pr[i1 - 1] + arr[i1];
    if (lPos[pr[i1] + 200000] == -1) {
      lPos[pr[i1] + 200000] = i1;
    } else {
      ans = max(ans, i1 - lPos[pr[i1] + 200000]);
    }
  }
}
vector<vector<int> > pose(200200);
int pref[200200];
int num[200200];
void solve() {
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
    cnt[a[i]]++;
    if (cnt[a[i]] > mx) {
      mx = cnt[a[i]];
      val = a[i];
    }
    pose[a[i]].push_back(i);
  }
  for (int i = 1; i <= n; i++) {
    if (cnt[i] >= (int)sqrt(n)) {
      lst.push_back(i);
    } else {
      bd.push_back(i);
    }
  }
  for (int i = 1; i <= n; i++) {
    pref[i] = pref[i - 1];
    if (a[i] == val) {
      arr[i] = -1;
      pref[i]++;
      num[pref[i]] = i;
    }
  }
  for (auto i : lst) {
    if (i == val) {
      continue;
    }
    tryBuild(i);
  }
  for (auto ch : bd) {
    if (ch == val) {
      continue;
    }
    for (int i = 0; i < pose[ch].size(); i++) {
      int x = pose[ch][i];
      for (int i1 = pose[ch].size() - 1; i1 >= i; i1--) {
        int y = pose[ch][i1];
        int cnt = i1 - i + 1 - (pref[y] - pref[x - 1]);
        if (cnt < 0) {
          continue;
        }
        int be = pref[x - 1];
        int all = pref[y];
        for (int i2 = 0; i2 <= cnt; i2++) {
          int l = (be < i2 ? 1 : num[be - i2] + 1);
          int r = (cnt - i2 + all >= mx ? n : num[cnt - i2 + all + 1] - 1);
          ans = max(ans, r - l + 1);
        }
      }
    }
  }
  cout << ans;
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  int q;
  q = 1;
  while (q != 0) {
    solve();
    --q;
  }
}
