↓あとで Accepted
int main() { int N, K; cin>>N>>K; VI w(N); REP(i, N) cin>>w[i]; int L=0, R=0; // [L, R) int maxi = -1; int maxv = 0; map<int, int> hi; ll ans = 0; while(1) { if(R==N) break; while(R<N && maxv<K) { R++; hi[w[R-1]]++; if(hi[w[R-1]] > maxv) { maxv = hi[w[R-1]]; maxi = w[R-1]; } } if(maxv<K) break; ans += N-R+1; //cout<<L<<" "<<R<<" + "<<N-R+1<<endl; while(L<N-1 && maxv == K) { L++; hi[w[L-1]]--; if(w[L-1]==maxi) {maxv--;break;} ans += N-R+1; } //cout<<L<<" "<<R<<endl; } cout<<ans<<endl; return 0; }