/* Solution Author: Grigory Reznikov Date: 29.04.2018 */ #include using namespace std; constexpr int MX = 500 * 1000 + 7; int a[MX]; int cnt[MX]; int cntcnt[MX]; int diff = 0; void ad(int x) { if (cnt[x] == 0) { diff++; cnt[x] = 1; cntcnt[1]++; } else { cntcnt[cnt[x]]--; cnt[x]++; cntcnt[cnt[x]]++; } } void rm(int x) { if (cnt[x] == 1) { diff--; cnt[x] = 0; cntcnt[1]--; } else { cntcnt[cnt[x]]--; cnt[x]--; cntcnt[cnt[x]]++; } } void cl() { memset(cnt, 0, sizeof(cnt)); memset(cntcnt, 0, sizeof(cntcnt)); diff = 0; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n; cin >> n; for (int i = 1; i <= n; i++) { cin >> a[i]; ad(a[i]); } int tdiff = diff; cl(); int lg = 1, rg = n + 1; while (rg - lg > 1) { int m = (lg + rg) >> 1; cl(); for (int i = 1; i <= m; i++) { ad(a[i]); } bool ok = false; if (diff == m || (m != n && diff != tdiff && diff == m - 1 && cntcnt[2] != 0)) { ok = true; } for (int i = m + 1; i <= n; i++) { ad(a[i]); rm(a[i - m]); if (diff == m || (m != n && diff != tdiff && diff == m - 1 && cntcnt[2] != 0)) { ok = true; } } if (ok) { lg = m; } else { rg = m; } } cout << lg << "\n"; }