I am trying to solve an algorithm problem:
Given an array
nums
of positive integers, call a (contiguous, not necessarily distinct) subarray ofnums
"good" if the number of different integers in that subarray is exactlyk
. For example,[1,2,3,1,2]
has3
different integers:1
,2
, and3
. Return the number of good subarrays ofnums
.
Looking at the solution here, I was able to come up with the following sliding window approach:
class Solution {
public:
int helper(vector<int>& nums, int B) {
unordered_map<int, int> m;
int start=0, end=0, count=0;
while(end<nums.size()) {
m[nums[end]]++;
while(m.size()>B) {
m[nums[start]]--;
if(m[nums[start]]<=0) m.erase(nums[start]);
start++;
}
count+=(end-start+1);
end++;
}
return count;
}
int subarraysWithKDistinct(vector<int>& nums, int k) {
return helper(nums, k)-helper(nums, k-1);
}
};
I understand how the helper()
function works, but not the intuition behind calculating number of subarrays with atmost k
and k-1
distinct integers and subtracting them (i.e., behind helper(nums, k)-helper(nums, k-1)
) to get the number of subarrays with exactly equal to k distinct integers.
What understanding am I missing?