#include <bits/stdc++.h>
template <typename T>
inline void read(T &x) {
  x = 0;
  char c = getchar();
  bool flag = false;
  while (!isdigit(c)) {
    if (c == '-') flag = true;
    c = getchar();
  }
  while (isdigit(c)) x = x * 10 + (c ^ 48), c = getchar();
  if (flag) x = -x;
}
using namespace std;
inline void MAX(int &a, int b) {
  if (a < b) a = b;
}
const int B = 250;
int n, a[201000];
vector<int> pos[201000];
int cnt[201000];
int mx = 0, mxp = 0;
int ans;
namespace jzpA {
int bin[201000 + 201000];
inline void sol(int col) {
  memset(bin, -1, sizeof(bin));
  bin[n] = 0;
  int x = 0, u = 0;
  for (int i = 1; i <= n; ++i) {
    if (a[i] == mxp)
      ++x;
    else if (a[i] == col)
      ++u;
    if (~bin[x - u + n])
      MAX(ans, i - bin[x - u + n]);
    else
      bin[x - u + n] = i;
  }
}
}  // namespace jzpA
namespace jzpB {
int h[201000];
inline void calc(int p, int x) {
  if (x < 0) return;
  MAX(ans, p - h[x]);
}
inline void sol(int col) {
  int lst = 0, sz = pos[col].size();
  for (unsigned int i = 0; i < pos[col].size(); lst = pos[col][i], ++i) {
    int p = pos[col][i];
    int ptr =
        lower_bound(pos[mxp].begin(), pos[mxp].end(), p) - pos[mxp].begin() - 1;
    p = ptr;
    memset(h, 0x3f, 4 * sz + 10);
    if (ptr < 0)
      h[0] = lst;
    else {
      for (int j = ptr; j >= 0 && ptr - j + 1 <= sz + 1; --j) {
        if (pos[mxp][j] < lst) {
          h[ptr - j] = lst;
          break;
        }
        h[ptr - j] = pos[mxp][j];
        if (j == 0) h[ptr + 1] = lst;
      }
    }
    int cha = 1;
    ptr = p + 1;
    if ((int)i != cnt[col] - 1) {
      for (unsigned int j = i + 1; j < pos[col].size(); ++j) {
        while (ptr < mx && ptr - p <= sz + 1 && pos[mxp][ptr] < pos[col][j])
          calc(pos[mxp][ptr++] - 1, cha), --cha;
        if (ptr - p > sz + 1) break;
        calc(pos[col][j] - 1, cha), ++cha;
        if (j == pos[col].size() - 1) {
          while (ptr - p <= sz + 1 && ptr < mx)
            calc(pos[mxp][ptr++] - 1, cha), --cha;
          if (ptr == mx) calc(n, cha);
        }
      }
    } else {
      while (ptr < mx && ptr - p <= sz + 1)
        calc(pos[mxp][ptr++] - 1, cha), --cha;
      if (ptr == mx) calc(n, cha);
    }
  }
}
}  // namespace jzpB
int main() {
  read(n);
  for (int i = 1; i <= n; ++i) {
    read(a[i]), pos[a[i]].push_back(i), ++cnt[a[i]];
    if (cnt[a[i]] > mx) mx = cnt[a[i]], mxp = a[i];
  }
  for (int i = 1; i <= n; ++i)
    if (pos[i].size() && i != mxp) {
      if (pos[i].size() > B)
        jzpA::sol(i);
      else
        jzpB::sol(i);
    }
  printf("%d\n", ans);
  return 0;
}
