Let’s try to fix the right endpoint first and then find the longest subarray for each right endpoint.
Let posx,i be the index of the i-th occurrence of number x. Assume the current right endpoint is r∈[0,n), for each x∈[1,C] The left endpoint can’t fall in the interval [posx,m−k+1+1,i] where m is the occurrence of x until r. This is because if left endpoint in that interval, the occurrence of x would be larger than zero and smaller than K, which doesn’t satisfy the constrain. We could add 1 on those intervals and the leftmost endpoint is the smallest index whose value is 0.
Now let’s consider how the intervals change when the right endpoint moves to r+1. It’s easy to see that only the interval for ar+1 will change.
The interval will change from [posar+1,m−k+1,posar+1,m−1] to [posar+1,m−k+1+1,posar+1,m]. Note that in the implementation we don’t have to change the overlapped interval.
In conclusion, we need a data structure that supports range modification and global minimum value query, a.k.a. segment tree.