A store shelf holds n items in a row, each labeled by an integer brand id. A restocking rule allows a contiguous stretch to mix at most k distinct brands. Find the length of the longest contiguous stretch that contains at most k distinct brand ids.
Line 1: two integers n and k.
Line 2: n space-separated integers, the brand ids in shelf order.
A single integer: the length of the longest contiguous window with at most k distinct values.
Example 1
Input
7 2 1 2 1 3 3 3 2
Expected
4
Explanation
The stretch [3, 3, 3, 2] uses only brands {3, 2} and has length 4; no longer stretch stays within 2 distinct brands.
Example 2
Input
5 1 4 4 4 4 4
Expected
5
Explanation
Only one brand exists, so the whole shelf of length 5 already satisfies the single-brand limit.
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 →