#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
long long int gcd(long long int a, long long int b) {
  if (!b)
    return a;
  else
    return gcd(b, a % b);
}
vector<int> a(211111);
int n;
int sol1(int x, int y) {
  int ans = 0;
  vector<int> b(n + 1);
  for (int i = 1; i <= n; i++) {
    if (a[i] == x) b[i] = 1;
    if (a[i] == y) b[i] = -1;
  }
  vector<int> seen(2 * n + 2, 1e9);
  int cur = 0;
  seen[0] = 0;
  for (int i = 1; i <= n; i++) {
    cur += b[i];
    int c = cur;
    if (c < 0) c = n - c;
    if (seen[c] == 1e9)
      seen[c] = i;
    else
      ans = max(ans, i - seen[c]);
  }
  return ans;
}
int sol2(int x) {
  int cur = 0;
  int ans = 0;
  vector<int> cnt(n + 1, 0);
  for (int l = 1, r = 1; r <= n; r++) {
    cnt[a[r]]++;
    if (cnt[a[r]] == x + 1) cur--;
    if (cnt[a[r]] == x) cur++;
    while (cnt[a[r]] > x) {
      cnt[a[l]]--;
      if (cnt[a[l]] == x) cur++;
      if (cnt[a[l]] == x - 1) cur--;
      l++;
    }
    if (cur > 1) ans = max(ans, r - l + 1);
  }
  return ans;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> n;
  vector<int> cnt(n + 1);
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
    cnt[a[i]]++;
  }
  int mx = 1;
  for (int i = 1; i <= n; i++) {
    if (cnt[mx] < cnt[i]) mx = i;
  }
  int m = sqrt(n);
  int ans = 0;
  for (int i = 1; i <= n; i++) {
    if (i == mx) continue;
    if (cnt[i] >= m) ans = max(ans, sol1(mx, i));
  }
  for (int i = 1; i < m; i++) {
    ans = max(ans, sol2(i));
  }
  cout << ans << '\n';
}
