#include <bits/stdc++.h>
using namespace std;
template <typename T>
inline void read(T &n) {
  T w = 1;
  n = 0;
  char ch = getchar();
  while (!isdigit(ch) && ch != EOF) {
    if (ch == '-') w = -1;
    ch = getchar();
  }
  while (isdigit(ch) && ch != EOF) {
    n = (n << 3) + (n << 1) + (ch & 15);
    ch = getchar();
  }
  n *= w;
}
template <typename T>
inline void write(T x) {
  T l = 0;
  unsigned long long y = 0;
  if (x < 0) {
    x = -x;
    putchar('-');
  }
  if (!x) {
    putchar(48);
    return;
  }
  while (x) {
    y = y * 10 + x % 10;
    x /= 10;
    l++;
  }
  while (l) {
    putchar(y % 10 + 48);
    y /= 10;
    l--;
  }
}
template <typename T>
inline void writes(T x) {
  write(x);
  putchar(' ');
}
template <typename T>
inline void writeln(T x) {
  write(x);
  puts("");
}
template <typename T>
inline void checkmax(T &a, T b) {
  a = a > b ? a : b;
}
template <typename T>
inline void checkmin(T &a, T b) {
  a = a < b ? a : b;
}
const int N = 2e5 + 10, MX = 2e5;
int a[N], sum[N], s[N], fi[2 * N], la[2 * N], ap[N], ans;
int main() {
  int n, mx = 0, mxi;
  read(n);
  int kuai = sqrt(n);
  for (int i = 1; i <= n; i++) {
    read(a[i]);
    sum[a[i]]++;
    if (sum[a[i]] > mx) {
      mx = sum[a[i]];
      mxi = a[i];
    }
  }
  for (int i = 1; i <= n; i++) {
    if (i == mxi) continue;
    if (sum[i] < kuai) continue;
    for (int j = 0; j <= 2 * MX; j++) fi[j] = la[j] = 0;
    for (int j = 1; j <= n; j++) {
      s[j] = s[j - 1];
      if (a[j] == mxi) s[j]++;
      if (a[j] == i) s[j]--;
      if (!fi[s[j] + MX]) fi[s[j] + MX] = j;
      la[s[j] + MX] = j;
    }
    fi[MX] = 0;
    for (int j = 0; j <= 2 * MX; j++) checkmax(ans, la[j] - fi[j]);
  }
  for (int i = 1; i <= kuai; i++) {
    int l = 0, no = 0;
    for (int j = 1; j <= n; j++) ap[j] = 0;
    for (int j = 1; j <= n; j++) {
      ap[a[j]]++;
      if (ap[a[j]] == i) {
        no++;
        if (no > 1) checkmax(ans, j - l);
        continue;
      }
      while (ap[a[j]] > i) {
        l++;
        if (ap[a[l]] == i) no--;
        ap[a[l]]--;
      }
      if (no > 1) checkmax(ans, j - l);
    }
  }
  writeln(ans);
  return 0;
}
