#include <bits/stdc++.h>
using namespace std;
const int BLK = 450;
const int HALF = 300000;
int bmap[600005], bval[600005];
int main() {
  int ver = 0;
  int n;
  scanf("%d", &n);
  vector<int> a(n + 1, 0);
  vector<int> acnt(n + 1, 0);
  vector<vector<int>> amap(n + 1, vector<int>());
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
    acnt[a[i]]++;
    amap[a[i]].push_back(i);
  }
  vector<pair<int, int>> ac(n + 1, {0, 0});
  for (int i = 1; i <= n; i++) ac[i] = {acnt[i], i};
  sort(ac.begin(), ac.end());
  reverse(ac.begin(), ac.end());
  if (ac[0].first == ac[1].first)
    printf("%d\n", n);
  else if (ac[0].first == n)
    printf("0\n");
  else {
    int mx = ac[0].second;
    int msz = ac[0].first;
    int ans = 0;
    for (int i = 1; i <= n; i++) {
      if (mx == i) continue;
      vector<int> b;
      int sz = acnt[i];
      int p = 0;
      for (int j = 0; j < sz; j++) {
        int k = lower_bound(amap[mx].begin(), amap[mx].end(), amap[i][j]) -
                amap[mx].begin();
        if (k > 0) {
          int k2 = k;
          int k3 = k;
          k3 -= (sz + 5);
          k3 = max(p, k3);
          for (int x = k3; x < k2; x++) b.push_back(amap[mx][x]);
          p = k2;
        }
        b.push_back(amap[i][j]);
        for (int x = k; x < k + (sz + 5); x++) {
          if (x >= msz) break;
          if (j + 1 < sz && amap[mx][x] >= amap[i][j + 1]) break;
          b.push_back(amap[mx][x]);
          p = x + 1;
        }
      }
      if (b.empty()) continue;
      if (b.back() != n) b.push_back(n);
      ver++;
      int bsum = 0;
      bval[0 + HALF] = ver;
      bmap[0 + HALF] = 0;
      int bprev = 0;
      for (auto it : b) {
        if (bval[bsum + HALF] == ver) {
          int br = it;
          int bl = bmap[bsum + HALF];
          int newans = br - bl - 1;
          if (bl != bprev && newans > ans) {
            if (newans >= 73788 && a[1] == 25) {
            }
            ans = newans;
          }
        }
        if (a[it] == mx)
          bsum++;
        else if (a[it] == i)
          bsum--;
        if (bval[bsum + HALF] == ver) {
          int br = it;
          int bl = bmap[bsum + HALF];
          int newans = br - bl;
          if (bl != bprev && newans > ans) {
            if (newans >= 73788 && a[1] == 25) {
            }
            ans = newans;
          }
        } else {
          bval[bsum + HALF] = ver;
          bmap[bsum + HALF] = it;
        }
        bprev = it;
      }
    }
    printf("%d\n", ans);
  }
  return 0;
}
