CSES - Shared codeLink to this code:
https://cses.fi/paste/04a60b88d87ca80723e799/
/*
Set time here:
Start: 2021-06-17 09:03:51
End(when AC):
*/
/*
Author: Shobhit Tewari
*/
#define __STDC_LIMIT_MACROS
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<unordered_map>
#include<queue>
#include<stack>
#include<cstring>
#include<algorithm>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<class T> using oset = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define int long long
#define null 0
#define fio ios_base::sync_with_stdio(false); cin.tie(null);
#define pb push_back
#define sz(v) (int)(v.size())
#define all(v) v.begin(), v.end()
template<class T> using PQ = priority_queue<T>;
template<class T> using RPQ = priority_queue<T, vector<T>, greater<T>>;
const int mod = 1e9 +7;
const int infinity = INT64_MAX;
const double pi = 3.1415926535897932384626433832795;
void solve(){
int n, k;
cin >> n >> k;
int arr[n];
for(int i=0;i<n;i++) cin >> arr[i];
int ans = 0;
unordered_map<int, int> mp;
int start = 0;
int end = 0;
int unique = 0;
while(end < n) {
mp[arr[end]]++;
if(mp[arr[end]] == 1) unique++;
if(unique > k) {
ans+=((end-start)*(end-start+1))/2;
while(start <= end && unique > k) {
mp[arr[start]]--;
if(mp[arr[start]] == 0) { unique--; }
start++;
}
ans-=((end-start)*(end-start+1))/2;
}
end++;
}
ans+=((end-start)*(end-start+1))/2;
cout << ans << "\n";
}
signed main(){
fio;
int t=1;
//cin >> t;
while(t--){
solve();
}
return 0;
}