#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 7;
int n, ans = 0, mx = 0;
int cnt[N];
int a[N];
int pos[2 * N];
int c[N];
void func1(int x) {
  int cur = 0;
  for (int i = 0; i <= 2 * n; i++) pos[i] = -1;
  pos[n] = 0;
  for (int i = 1; i <= n; i++) {
    if (a[i] == x)
      cur--;
    else if (a[i] == mx)
      cur++;
    if (pos[n + cur] == -1) pos[n + cur] = i;
    ans = max(ans, i - pos[n + cur]);
  }
}
void func2(int x) {
  for (int i = 1; i <= n; i++) c[i] = 0;
  int l = 1, cmost = 0;
  for (int i = 1; i <= n; i++) {
    c[a[i]]++;
    if (c[a[i]] == x)
      cmost++;
    else if (c[a[i]] > x) {
      cmost--;
      while (c[a[i]] > x) {
        c[a[l]]--;
        if (c[a[l]] == x)
          cmost++;
        else if (c[a[l]] == x - 1)
          cmost--;
        l++;
      }
    }
    if (cmost >= 2) ans = max(ans, i - l + 1);
  }
}
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
    cnt[a[i]]++;
    mx = cnt[mx] < cnt[a[i]] ? a[i] : mx;
  }
  int lim = sqrt(n);
  for (int i = 1; i <= n; i++)
    if (cnt[i] >= lim && mx != i) func1(i);
  for (int i = 1; i < lim; i++) func2(i);
  cout << ans;
  return 0;
}
