#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  scanf("%d", &n);
  vector<int> a(n + 1);
  int maxcnt = 0, maxa = -1;
  vector<int> cnt(n + 1);
  vector<int> val;
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
    if (cnt[a[i]] == 0) {
      val.push_back(a[i]);
    }
    cnt[a[i]]++;
    if (cnt[a[i]] > maxcnt) {
      maxcnt = cnt[a[i]];
      maxa = a[i];
    } else if (cnt[a[i]] == maxcnt) {
      maxa = -1;
    }
  }
  if (maxa == -1) {
    printf("%d\n", n);
    return 0;
  }
  vector<int> x(n + 1);
  vector<int> sum(n + 1);
  int ans = 0;
  int up = 450;
  if (maxcnt >= up) {
    for (auto o : val) {
      if (cnt[o] >= up && o != maxa) {
        vector<int> pos(2 * n + 1, -1);
        pos[n] = 0;
        for (int i = 1; i <= n; i++) {
          if (a[i] == maxa) {
            x[i] = 1;
          } else if (a[i] == o) {
            x[i] = -1;
          } else {
            x[i] = 0;
          }
          sum[i] = sum[i - 1] + x[i];
          if (pos[sum[i] + n] == -1) {
            pos[sum[i] + n] = i;
          } else {
            ans = max(ans, i - pos[sum[i] + n]);
          }
        }
      }
    }
  }
  for (int t = 1; t <= up; t++) {
    vector<int> nowcnt(n + 1);
    vector<int> nowcntcnt(t + 1);
    int le = 1, ri = 1;
    while (ri <= n) {
      nowcntcnt[nowcnt[a[ri]]]--;
      nowcnt[a[ri]]++;
      nowcntcnt[nowcnt[a[ri]]]++;
      while (le < ri && nowcnt[a[ri]] > t) {
        nowcntcnt[nowcnt[a[le]]]--;
        nowcnt[a[le]]--;
        nowcntcnt[nowcnt[a[le]]]++;
        le++;
      }
      if (nowcntcnt[t] > 1) {
        ans = max(ans, ri - le + 1);
      }
      ri++;
    }
  }
  printf("%d\n", ans);
  return 0;
}
