class Solution {
private:
int numOfMostKDistinct(vector<int>& nums, int k) {
int n = nums.size();
int res = 0, kinds = 0;
vector<int> cnts(2e4+1, 0);
for (int left = 0, right = 0; right < n; right++) {
if (++cnts[nums[right]] == 1) kinds++;
while (kinds > k) {
if (--cnts[nums[left++]] == 0) {
kinds--;
}
}
res += right - left + 1;
}
return res;
}
public:
int subarraysWithKDistinct(vector<int>& nums, int k) {
return numOfMostKDistinct(nums, k) - numOfMostKDistinct(nums, k - 1);
}
};