#include <bits/stdc++.h>
using namespace std;
using namespace std;
const int maxn = 1e5 + 5;
const int N = 2e5 + 7;
const int M = N << 1;
int K = 400;
int cnt[N], a[N], tp[N], ret, rt;
void Add(int x, int k) {
  ret -= (tp[x] == rt);
  tp[x] += k;
  ret += (tp[x] == rt);
}
int main() {
  int n, x, ans = 0;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    cnt[--a[i]]++;
  }
  x = max_element(cnt, cnt + n) - cnt;
  for (rt = 1; rt <= K; rt++) {
    memset(tp, 0, sizeof(tp));
    ret = 0;
    for (int l = 0, r = 0; r < n; r++) {
      Add(a[r], 1);
      while (tp[a[r]] > rt) Add(a[l], -1), l++;
      if (ret > 1) ans = max(ans, r - l + 1);
    }
  }
  for (int i = 0; i < n; i++) {
    if (cnt[i] < K || i == x) continue;
    vector<int> v(2 * n + 7, n);
    v[n] = 0;
    int cur = n;
    for (int j = 0; j < n; j++) {
      cur += a[j] == x ? -1 : a[j] == i ? 1 : 0;
      ans = max(ans, j + 1 - v[cur]);
      if (v[cur] == n) v[cur] = j + 1;
    }
  }
  printf("%d\n", ans);
}
