#include <bits/stdc++.h>
using namespace std;
const int MAXN = 200010;
int n, ans = 0;
int f[MAXN + MAXN];
vector<int> x;
vector<int> y[MAXN];
int bruteforce(int t, int p) {
  memset(f, -1, sizeof(f));
  f[MAXN] = 0;
  int cnt = MAXN, ans = 0;
  for (int i = 1; i <= n; ++i) {
    if (x[i] == p) {
      ++cnt;
    } else if (x[i] == t) {
      --cnt;
    }
    if (f[cnt] != -1) {
      ans = max(ans, i - f[cnt]);
    } else {
      f[cnt] = i;
    }
  }
  return ans;
}
int countpos(int t, int p) {
  vector<pair<int, int>> s;
  int n = y[t].size(), j = 1, ans = 0;
  y[t].push_back(y[p].back());
  for (int i = 0; i < n; ++i) {
    int pos = upper_bound(y[p].begin(), y[p].end(), y[t][i]) - y[p].begin();
    bool skipped = false;
    if (j < pos - n - 1) {
      j = pos - n - 1;
      skipped = true;
    }
    if (i == 0 && j == 1) s.push_back(make_pair(0, 0));
    for (; j < pos; ++j) {
      if (skipped) {
        s.push_back(make_pair(y[p][j], 10));
        skipped = false;
      } else {
        s.push_back(make_pair(y[p][j], 1));
      }
    }
    s.push_back(make_pair(y[t][i], -1));
    for (; j < min(pos + n + 1, (int)y[p].size()); ++j) {
      if (y[t][i + 1] < y[p][j]) break;
      s.push_back(make_pair(y[p][j], 1));
    }
  }
  int m = s.size();
  vector<int> h(m + m + 5, -1);
  int cnt = 0;
  for (int i = 0; i < s.size(); ++i) {
    if (h[m + cnt] != -1 && s[i].second != 10) {
      ans = max(ans, s[i].first - 1 - h[m + cnt]);
    }
    if (s[i].first == y[p].back()) break;
    if (s[i].second == 10) s[i].second = 1;
    cnt += s[i].second;
    if (h[m + cnt] != -1) {
      ans = max(ans, s[i].first - h[m + cnt]);
    } else {
      h[m + cnt] = s[i].first;
    }
  }
  return ans;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cin >> n;
  x = vector<int>(n + 1, 0);
  for (int i = 1; i <= n; ++i) {
    cin >> x[i];
    y[x[i]].push_back(i);
  }
  int cnt = 0, p = 0;
  for (int i = 1; i <= n; ++i) {
    if (y[i].size() > cnt) {
      cnt = y[i].size();
      p = i;
    }
  }
  y[p].insert(y[p].begin(), 0);
  y[p].push_back(n + 1);
  int sqrtn = sqrt(n);
  for (int i = 1; i <= n; ++i) {
    if (i == p || y[i].size() == 0) continue;
    if (y[i].size() >= sqrtn) {
      ans = max(ans, bruteforce(i, p));
    } else {
      ans = max(ans, countpos(i, p));
    }
  }
  cout << ans << endl;
  return 0;
}
