#include <bits/stdc++.h>
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")
#pragma GCC target( \
    "sse,sse2,sse3,ssse3,sse4.1,sse4.2,avx,avx2,popcnt,tune=native")
using namespace std;
int n, ct[200020], a[200020], smx, id, b[200020], ans;
vector<int> p[200020];
int mx[200020 << 2], mn[200020 << 2], ad[200020 << 2];
inline void up(int k) {
  mx[k] = max(mx[k << 1], mx[k << 1 | 1]);
  mn[k] = min(mn[k << 1], mn[k << 1 | 1]);
}
inline void down(int k) {
  ad[k << 1] += ad[k], ad[k << 1 | 1] += ad[k];
  mx[k << 1] += ad[k], mx[k << 1 | 1] += ad[k];
  mn[k << 1] += ad[k], mn[k << 1 | 1] += ad[k];
  ad[k] = 0;
}
inline void build(int k, int l, int r) {
  if (l == r) {
    mx[k] = mn[k] = b[l];
    return;
  }
  int m = l + r >> 1;
  build(k << 1, l, m), build(k << 1 | 1, m + 1, r), up(k);
}
void Add(int k, int l, int r, int L, int R, int v) {
  if (l >= L && r <= R) {
    mx[k] += v, mn[k] += v, ad[k] += v;
    return;
  }
  if (ad[k]) down(k);
  int m = l + r >> 1;
  if (L <= m) Add(k << 1, l, m, L, R, v);
  if (R > m) Add(k << 1 | 1, m + 1, r, L, R, v);
  up(k);
}
int ask(int k, int l, int r, int v) {
  if (l == r) return mx[k];
  if (ad[k]) down(k);
  int m = l + r >> 1;
  if (v <= m)
    return ask(k << 1, l, m, v);
  else
    return ask(k << 1 | 1, m + 1, r, v);
}
int askr(int k, int l, int r, int v) {
  if (l == r) return l;
  if (ad[k]) down(k);
  int m = l + r >> 1;
  if (mx[k << 1 | 1] >= v && mn[k << 1 | 1] <= v)
    return askr(k << 1 | 1, m + 1, r, v);
  else
    return askr(k << 1, l, m, v);
}
int askl(int k, int l, int r, int v) {
  if (l == r) return l;
  if (ad[k]) down(k);
  int m = l + r >> 1;
  if (mx[k << 1] >= v && mn[k << 1] <= v)
    return askl(k << 1, l, m, v);
  else
    return askl(k << 1 | 1, m + 1, r, v);
}
set<int> s;
inline void work(int V) {
  s.clear();
  for (auto v : p[V]) Add(1, 1, n, v, n, 1);
  for (auto v : p[V]) {
    s.insert(ask(1, 1, n, v));
    s.insert(ask(1, 1, n, max(1, v - 1)));
    s.insert(ask(1, 1, n, min(n, v + 1)));
  }
  for (auto v : s) ans = max(ans, askr(1, 1, n, v) - askl(1, 1, n, v));
  for (auto v : p[V]) Add(1, 1, n, v, n, -1);
}
int main() {
  scanf("%d", &n), ++n;
  for (int i = 2; i <= n; ++i) {
    scanf("%d", &a[i]);
    ++ct[a[i]], p[a[i]].push_back(i);
    if (ct[a[i]] > smx) smx = ct[a[i]], id = a[i];
  }
  for (int i = 1; i <= n; ++i) {
    b[i] = 0;
    if (a[i] == id) b[i] = -1;
    b[i] += b[i - 1];
  }
  build(1, 1, n);
  for (int i = 1; i <= n; ++i)
    if (ct[i]) {
      if (i == id) continue;
      work(i);
    }
  printf("%d\n", ans);
}
