#include <bits/stdc++.h>
using namespace std;
template <class Type>
long long quick_pow(Type x, Type y, Type Mod) {
  long long res = 1;
  while (y) {
    if (y & 1) res = res * x % Mod;
    x = x * x % Mod, y >>= 1;
  }
  return res;
}
template <class Type>
long long inv(Type x, Type Mod) {
  return quick_pow(x, Mod - 2, Mod);
}
namespace IO {
template <class T>
inline void read(T &x) {
  x = 0;
  int f = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch <= '9' && ch >= '0') x = x * 10 + ch - '0', ch = getchar();
  x *= f;
}
};  // namespace IO
using namespace IO;
const int N = 500005;
const int M = 200005;
int n, A[N], Mx, tag[N];
vector<int> vec[N];
const int B = 500;
int ans;
void solve1(int K) {
  memset(tag, -1, sizeof(tag));
  int cur = 0;
  tag[cur + M] = 0;
  for (int i = (1); i <= (n); ++i) {
    if (A[i] == Mx) cur++;
    if (A[i] == K) cur--;
    if (tag[cur + M] == -1)
      tag[cur + M] = i;
    else
      ans = max(ans, i - tag[cur + M]);
  }
}
int cnt[N], num[N];
int main() {
  read(n);
  for (int i = (1); i <= (n); ++i) read(A[i]), vec[A[i]].push_back(i);
  for (int i = (1); i <= (n); ++i) {
    if (vec[Mx].size() < vec[i].size()) Mx = i;
  }
  for (int i = (1); i <= (n); ++i) {
    if (i != Mx && vec[i].size() == vec[Mx].size()) {
      cout << n << endl;
      return 0;
    }
  }
  for (int i = (1); i <= (n); ++i)
    if (i != Mx) {
      if (vec[i].size() >= B) solve1(i);
    }
  for (int i = (1); i <= (B); ++i) {
    int Mxnum = 0, res = 0;
    for (int j = (1); j <= (n); ++j) cnt[j] = 0, num[j] = 0;
    num[0] = n;
    for (int j = 1, k = 1; j <= n; j++) {
      while (k <= n && res + (A[k] == Mx) <= i) {
        num[cnt[A[k]]]--;
        cnt[A[k]]++;
        num[cnt[A[k]]]++;
        Mxnum = max(Mxnum, cnt[A[k]]);
        res += (A[k] == Mx);
        k++;
      }
      if (Mxnum == cnt[Mx] && num[Mxnum] >= 2) {
        ans = max(ans, k - j);
      }
      num[cnt[A[j]]]--;
      if (num[cnt[A[j]]] == 0) Mxnum--;
      cnt[A[j]]--;
      num[cnt[A[j]]]++;
      res -= (A[j] == Mx);
    }
  }
  cout << ans << endl;
  return 0;
}
