A gelato truck logs the flavor ID (a positive integer) of every scoop it sells during the day, in order, as an array of n integers. Given a limit K, find the length of the longest contiguous window of sales that contains at most K distinct flavor IDs.
Line 1: two integers n and K.
Line 2: n space-separated positive integers, the flavor IDs sold in order.
A single integer: the length of the longest contiguous subarray containing at most K distinct flavor IDs. If K is 0, the answer is 0.
Example 1
Input
6 2 1 1 2 2 3 3
Expected
4
Explanation
Both [1,1,2,2] (positions 1-4) and [2,2,3,3] (positions 3-6) have exactly 2 distinct flavors and length 4, which is the longest possible with at most 2 distinct flavors.
Example 2
Input
4 1 5 5 5 5
Expected
4
Explanation
The whole run has only 1 distinct flavor, satisfying K=1, so the answer is the full length 4.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →