#include <bits/stdc++.h>
using namespace std;
const int mod = 998244353;
const int maxn = 2e5 + 10;
const int inf = 0x3f3f3f3f;
const double eps = 1e-6;
int n, a[maxn];
int num[maxn];
int b = 500;
int pre[maxn];
int lst[maxn << 1];
int up = 500;
int mx = 0;
int c0[maxn], c[maxn];
void add(int x) {
  c0[c[x]]--;
  c[x]++;
  c0[c[x]]++;
  mx = max(mx, c[x]);
}
void sub(int x) {
  c0[c[x]]--;
  c[x]--;
  c0[c[x]]++;
  mx -= (c0[mx] == 0);
}
int solve1(int D) {
  int ans = 0;
  for (int i = 1; i <= 500; i++) {
    for (int j = 1; j <= n; j++) c[j] = c0[j] = 0;
    c0[mx = 0] = n;
    for (int j = 1, k = 1, x = 0; j <= n; j++) {
      while (k <= n && x + (a[k] == D) <= i) add(a[k]), x += (a[k] == D), ++k;
      c0[mx] >= 2 ? ans = max(ans, k - j), 0 : 0, sub(a[j]), x -= (a[j] == D);
    }
  }
  return ans;
}
int solve2(int mx) {
  int ans = 0;
  int fix = 2e5;
  for (int i = 1; i <= n; i++)
    if (i != mx && num[i] >= 512) {
      for (int j = -n; j <= n; j++) lst[j + fix] = -1;
      lst[fix] = 0;
      int sum = 0;
      for (int j = 1; j <= n; j++) {
        sum += (a[j] == mx);
        sum -= (a[j] == i);
        if (lst[sum + fix] >= 0)
          ans = max(ans, j - lst[sum + fix]);
        else
          lst[sum + fix] = j;
      }
    }
  return ans;
}
int main() {
  std::ios::sync_with_stdio(false), cin.tie(0);
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i], num[a[i]]++;
  int mx = 0, mx_id = 0, cnt = 0;
  for (int i = 1; i <= n; i++) {
    if (num[i] > mx)
      mx = num[i], mx_id = i, cnt = 1;
    else if (num[i] == mx)
      cnt++;
  }
  if (cnt > 1) {
    cout << n << '\n';
    return 0;
  }
  int D = mx_id;
  cout << max(solve1(D), solve2(D)) << '\n';
  return 0;
}
