C++ Sliding Window
Again it makes it easier to count subarrays with maximum(at-most) K different elements rather than counting subarrays with exactly K different elements. Reason 
Again it makes it easier to count subarrays with maximum(at-most) `K` different elements rather than counting subarrays with exactly `K` different elements. Reason - we can keep incrementing our subarray count till we reach `K+1` different elements.\nIf on the other hand we had to count exactly `K` different elements, our subarray count will increase only upon reaching `K` different elements and we will have to check if the next element in the array is different from the elements that we already have in our map, i.e. if it will change our count of different elements or not.\n\n`unordered_map` - to store frequency of elements. Its size tells us the number of different elements.\n`j` - to add new elements\n`i` - remove elements from map when the number of different elements exceeds `K`.\n\n```\nint atMostKDistinct(vector<int>& arr, int k) {\n        unordered_map<int, int> mp;\n        int n = arr.size();\n        int i=0, j=0;\n        int count = 0;\n        \n        while(j < n) {\n            mp[arr[j++]] += 1;\n            while(mp.size() > k) {\n                if(mp[arr[i]] == 1)\n                    mp.erase(arr[i++]);\n                else\n                    mp[arr[i++]] -= 1;\n            }\n            count += j-i;\n        }\n        return count;\n    }\n    int subarraysWithKDistinct(vector<int>& nums, int k) {\n        return atMostKDistinct(nums, k) - atMostKDistinct(nums, k-1);\n    }\n```\n\nNumber of subarrays in array of n elements = `n*(n+1)/2`\n`count += j-i` takes care of that.\nI \'`erase`\' the element from map when its frequency is 1, otherwise just decrement the frequency.\n\nExact `K` subarrays = (at-most `K` subarrays) - (at-most `K-1` subarrays).\n\nI hope my explanation was readable and understandable.
[]