#include <bits/stdc++.h>
using namespace std;
const int maxn = 200005;
const int inf = 0x3f3f3f3f;
const int mod = 1e9 + 7;
int a[maxn], cnt[maxn];
vector<int> pos[maxn];
int lst[maxn], nxt[maxn];
int n;
int sum[maxn], pre[maxn * 2];
struct node {
  int w, idx;
};
void addLast(int u, int sz, vector<node> &vec) {
  if (sz == 0) return;
  if (u <= vec[vec.size() - 1].idx) return;
  addLast(lst[u], sz - 1, vec);
  vec.push_back(node{1, u});
}
void addNext(int u, int sz, int up, vector<node> &vec) {
  if (sz == 0) return;
  if (u >= up) return;
  vec.push_back(node{1, u});
  addNext(nxt[u], sz - 1, up, vec);
}
int solve(int d, int v) {
  int szv = pos[v].size();
  vector<node> vec;
  vec.push_back(node{0, 0});
  for (int i = 0; i < szv; i++) {
    addLast(lst[pos[v][i]], szv + 1, vec);
    vec.push_back(node{-1, pos[v][i]});
    int up = i == szv - 1 ? n + 1 : pos[v][i + 1];
    addNext(nxt[pos[v][i]], szv + 1, up, vec);
  }
  vec.push_back(node{0, n + 1});
  sum[0] = n;
  for (int i = 1; i < vec.size(); i++) {
    sum[i] = sum[i - 1] + vec[i].w;
  }
  pre[n] = 0;
  int ans = 0;
  for (int i = 1; i < vec.size() - 1; i++) {
    if (pre[sum[i]] != -1) {
      ans = max(ans, vec[i + 1].idx - 1 - vec[pre[sum[i]]].idx);
    } else {
      pre[sum[i]] = i;
    }
  }
  for (int i = 1; i < vec.size(); i++) {
    pre[sum[i]] = -1;
  }
  return ans;
}
int main() {
  scanf("%d", &n);
  for (int i = 0; i <= 2 * n; i++) {
    pre[i] = -1;
  }
  for (int i = 1; i <= n; i++) {
    scanf("%d", a + i);
    cnt[a[i]]++;
    pos[a[i]].push_back(i);
  }
  int mx = 0;
  for (int i = 1; i <= n; i++) {
    if (cnt[i] > cnt[mx]) {
      mx = i;
    }
  }
  int tmp = 0;
  for (int i = 1; i <= n; i++) {
    if (cnt[mx] == cnt[i]) {
      tmp++;
    }
  }
  if (tmp > 1) {
    printf("%d\n", n);
    return 0;
  }
  int p = 0;
  for (int i = 1; i <= n; i++) {
    lst[i] = p;
    if (a[i] == mx) {
      p = i;
    }
  }
  p = n + 1;
  for (int i = n; i >= 1; i--) {
    nxt[i] = p;
    if (a[i] == mx) {
      p = i;
    }
  }
  int ans = 0;
  for (int i = 1; i <= n; i++) {
    if (cnt[i] == 0) continue;
    if (mx == i) continue;
    ans = max(ans, solve(mx, i));
  }
  printf("%d\n", ans);
  return 0;
}
