#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 2e5 + 5;
const int mod = 1e9 + 7;
const double eps = 1e-8;
int n;
int a[maxn];
int num[maxn], nm[maxn];
int mp[maxn * 2];
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) scanf("%d", &a[i]), num[a[i]]++;
  int cnt, cnr = 0;
  bool f = 0;
  for (int i = 1; i <= n; ++i) {
    if (!num[i]) continue;
    if (num[i] > cnr) {
      cnr = num[i];
      cnt = i;
      f = 0;
    } else if (num[i] == cnr && cnt != i)
      f = 1;
  }
  if (f) {
    printf("%d\n", n);
    return 0;
  }
  int ans = 0, p = sqrt(n * 1.0);
  for (int i = 1; i <= n; ++i) {
    if (!num[i]) continue;
    if (i == cnt) continue;
    if (num[i] < p) continue;
    int sum = maxn;
    for (int j = 0; j <= 2 * maxn; ++j) mp[j] = 0;
    for (int j = 1; j <= n; ++j) {
      if (a[j] == i)
        sum--;
      else if (a[j] == cnt)
        sum++;
      if (!mp[sum]) mp[sum] = j;
      if (sum != maxn && mp[sum] != 0)
        ans = max(ans, j - mp[sum]);
      else if (sum == maxn)
        ans = max(ans, j);
    }
  }
  for (int i = 1; i <= p; ++i) {
    int l = 1, r = 0;
    for (int j = 1; j <= n; ++j) nm[j] = 0;
    for (int j = 1; j <= n; ++j) {
      if (++nm[a[j]] == i) r++;
      while (l <= j && nm[a[j]] > i) {
        if (nm[a[l++]]-- == i) r--;
      }
      if (r >= 2) ans = max(ans, j - l + 1);
    }
  }
  printf("%d\n", ans);
  return 0;
}
