<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the number of <strong>good subarrays</strong> of </em><code>nums</code>.</p>

<p>A <strong>good array</strong> is an array where the number of different integers in that array is exactly <code>k</code>.</p>

<ul>
	<li>For example, <code>[1,2,3,1,2]</code> has <code>3</code> different integers: <code>1</code>, <code>2</code>, and <code>3</code>.</li>
</ul>

<p>A <strong>subarray</strong> is a <strong>contiguous</strong> part of an array.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,1,2,3], k = 2
<strong>Output:</strong> 7
<strong>Explanation:</strong> Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,1,3,4], k = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li>
	<li><code>1 &lt;= nums[i], k &lt;= nums.length</code></li>
</ul>

#include<vector>
#include<unordered_map>
#include<unordered_set>
using namespace std;

class Solution {
public:
    int subarraysWithKDistinct(vector<int>& nums, int k) {
        int INF = 1000000;
        vector<int> distance(k,0);//with init
        //vector<int> pivot(nums.size(),0);//first element of the max subseq with this k length
        vector<int> inclusion(nums.size()+1,INF);//all sequence lengths above include k
        vector<int> inclu_inv(k+1,0);//invert the above, but only up to k
        int counter = 0;
        for (int num: nums){
            //for (int k: inclusion) cout << k << " ";
            //cout << endl;
            int incl = inclusion[num];
            for (int j=k-1;j>0;j--){
                if (j < incl){
                    //if not included, shift pivots
                    //pivot[j] = pivot[j-1];//cutoff
                    distance[j] = distance[j-1]+1;
                } else{
                    distance[j]++;//if included, just increment
                }
            }
            //j=0 case
            distance[0]++;
            if (incl > 0){
                //pivot[0] = num;
                distance[0] = 1;
            }
            for (int j=k-1;j>=0;j--){
                //cout << "flag:"<< inclu_inv[j] << endl;
                if (inclusion[inclu_inv[j]]<incl){
                    inclusion[inclu_inv[j]]+=1;
                    inclu_inv[j+1] = inclu_inv[j];
                }
            }
            inclusion[num] = 0;
            inclu_inv[0] = num;
            if (k > 1){
                counter += distance[k-1]-distance[k-2];
            } else{
                counter += distance[k-1];
            }
        }
        return counter;
    }
};
41504