#include <bits/stdc++.h>
using namespace std;
using namespace std;
inline int read() {
  char ch;
  bool sign = 0;
  int res = 0;
  while (!isdigit(ch = getchar()))
    if (ch == '-') sign = 1;
  while (isdigit(ch)) res = res * 10 + (ch ^ 48), ch = getchar();
  if (sign)
    return -res;
  else
    return res;
}
mt19937 Rnd(chrono::system_clock::now().time_since_epoch().count());
const int maxn = 200000 + 10;
const int inf = 1e9;
const int MAXM = 3;
const long long MOD[] = {469762049, 998244353, 1004535809, 1000000007};
const int mod = 1811939329;
const int apsz = 26;
int a[maxn], n, cnt[maxn], Sqrt;
int mx;
inline int brute(int x) {
  vector<int> pos(2 * n + 2, -1);
  int now = maxn;
  int ans = 0;
  pos[n] = 0;
  for (auto i = (1); i <= (n); ++i) {
    if (now == maxn && a[i] != x && a[i] != mx) continue;
    if (now == maxn) now = 0;
    if (a[i] == x) {
      now++;
    } else if (a[i] == mx)
      now--;
    if (pos[now + n] >= 0) ans = max(ans, i - pos[now + n]);
    if (pos[now + n] == -1) pos[now + n] = i;
  }
  return ans;
}
inline int gao(int c) {
  memset(cnt, 0, sizeof(cnt));
  int has = 0;
  int l, r, ans;
  for (ans = 0, r = l = 1; r <= n; ++r) {
    ++cnt[a[r]];
    if (cnt[a[r]] == c)
      has++;
    else if (cnt[a[r]] == c + 1)
      has--;
    while (cnt[a[r]] > c) {
      --cnt[a[l]];
      if (cnt[a[l]] == c) has++;
      if (cnt[a[l]] == c - 1) has--;
      l++;
    }
    assert(has >= 0 && r >= l);
    if (has > 1) ans = max(ans, r - l + 1);
  }
  return ans;
}
inline int solve() {
  int mxcnt = 0;
  for (auto i = (1); i <= (n); ++i) {
    if (++cnt[a[i]] > mxcnt) mxcnt = cnt[a[i]], mx = a[i];
  }
  for (auto i = (1); i <= (n); ++i) {
    if (mx != a[i] && cnt[a[i]] == mxcnt) return n;
  }
  int ans(0);
  Sqrt = sqrt(n + 3);
  for (auto i = (1); i <= (n); ++i) {
    if (cnt[a[i]] >= Sqrt && a[i] != mx) {
      ans = max(brute(a[i]), ans);
      cnt[a[i]] = 0;
    }
  }
  for (auto c = (1); c <= (Sqrt); ++c) {
    ans = max(ans, gao(c));
  }
  return ans;
}
int main(void) {
  scanf("%d", &(n));
  for (auto i = (1); i <= (n); ++i) scanf("%d", &(a[i]));
  printf("%d\n", solve());
  return 0;
}
