#include <bits/stdc++.h>
const int N = 1000005;
int n, t, ai[N];
inline void read(int &x) {
  register char ch = 0;
  register bool w = 0;
  for (x = 0; !std::isdigit(ch); w |= ch == '-', ch = getchar())
    ;
  for (; std::isdigit(ch); x = x * 10 + ch - '0', ch = getchar())
    ;
  (w) && (x = -x);
  return;
}
int occ[N];
int main() {
  read(n);
  for (int i = 1; i <= n; ++i) read(ai[i]), ++occ[ai[i]];
  int mxc = 0, count1 = 0, d = -1;
  for (int i = 1; i <= n; ++i) {
    mxc = std::max(mxc, occ[i]);
  }
  for (int i = 1; i <= n; ++i) {
    if (occ[i] == mxc) {
      ++count1;
      d = i;
    }
  }
  if (count1 > 1) {
    printf("%d\n", n);
    return 0;
  }
  std::vector<int> deal;
  int limit = 450;
  for (int i = 1; i <= n; ++i) {
    if (occ[i] > limit) {
      deal.push_back(i);
    }
  }
  static int mp[N], pre[N], cnt[N];
  int ans = 0;
  for (auto now : deal) {
    for (int i = 0; i <= 2 * n; ++i) mp[i] = n + 5, pre[i] = 0;
    mp[n] = 0;
    for (int i = 1; i <= n; ++i) {
      int x = 0;
      if (ai[i] == now)
        x = 1;
      else if (ai[i] == d)
        x = -1;
      pre[i] = pre[i - 1] + x;
      ans = std::max(ans, i - mp[pre[i] + n]);
      if (mp[pre[i] + n] > n) mp[pre[i] + n] = i;
    }
  }
  for (int oc = 1; oc <= limit; ++oc) {
    for (int i = 1; i <= n; ++i) cnt[i] = 0, occ[i] = 0;
    int p1 = 1;
    for (int i = 1; i <= n; ++i) {
      --cnt[occ[ai[i]]], ++occ[ai[i]], ++cnt[occ[ai[i]]];
      while (p1 <= i && occ[ai[i]] > oc) {
        --cnt[occ[ai[p1]]], --occ[ai[p1]], ++cnt[occ[ai[p1]]];
        ++p1;
      }
      if (cnt[oc] >= 2) {
        ans = std::max(ans, i - p1 + 1);
      }
    }
  }
  printf("%d\n", ans);
  return 0;
}
