#include <bits/stdc++.h>
using namespace std;
int N;
int A[202020];
vector<int> P[202020];
set<int> S;
int id[404040];
int pos[404040];
void solve() {
  int i, j, k, l, r, x, y;
  string s;
  cin >> N;
  for (i = 0; i < (N); i++) {
    cin >> A[i];
    A[i]--;
    P[A[i]].push_back(i);
  }
  int ma = 0, num = -1;
  for (i = 0; i < (N); i++) ma = max(ma, (int)P[i].size());
  x = -1;
  for (i = 0; i < (N); i++)
    if (P[i].size() == ma) {
      if (x == -1) {
        x = i;
        for (auto& p : P[i]) S.insert(p);
      } else {
        cout << N << endl;
        return;
      }
    }
  memset(id, 0xff, sizeof(id));
  S.insert(N);
  int ret = 0;
  for (i = 0; i < (N); i++) {
    if (i == x || P[i].empty()) continue;
    if (P[i].size() <= 400) {
      for (auto& p : P[i]) S.insert(p);
      for (auto& p : P[i]) {
        auto it = S.find(p);
        map<int, int> M;
        int cur = 0;
        for (j = 0; j < (P[i].size() + 1); j++) {
          if (it == S.begin()) {
            M[cur] = 0;
            break;
          }
          it--;
          M[cur] = *it + 1;
          if (A[*it] == x) cur--;
          if (A[*it] == i) break;
        }
        it = S.find(p);
        cur = 0;
        for (j = 0; j < (P[i].size() * 2 + 1); j++) {
          y = *it;
          if (M.count(cur)) ret = max(ret, y - M[cur]);
          if (y == N) break;
          if (A[y] == x)
            cur++;
          else
            cur--;
          it++;
        }
      }
      for (auto& p : P[i]) S.erase(p);
    } else {
      int cur = 202020;
      id[cur] = i;
      pos[cur] = 0;
      for (j = 0; j < (N); j++) {
        if (A[j] == i) cur++;
        if (A[j] == x) cur--;
        if (id[cur] == i)
          ret = max(ret, j + 1 - pos[cur]);
        else
          id[cur] = i, pos[cur] = j + 1;
      }
    }
  }
  cout << ret << endl;
}
int main(int argc, char** argv) {
  string s;
  int i;
  if (argc == 1) ios::sync_with_stdio(false), cin.tie(0);
  for (i = 0; i < (argc - 1); i++) s += argv[i + 1], s += '\n';
  for (i = 0; i < (s.size()); i++) ungetc(s[s.size() - 1 - i], stdin);
  cout.tie(0);
  solve();
  return 0;
}
