#K62067. Maximum Length Subarray with At Most K Distinct Integers
Maximum Length Subarray with At Most K Distinct Integers
Maximum Length Subarray with At Most K Distinct Integers
Given an array of integers A = [a1, a2, …, an] and an integer K, find the maximum length of a contiguous subarray such that it contains at most K distinct integers. In mathematical terms, if we denote a subarray A[i...j], you need to determine the maximum value of (j - i + 1) subject to the constraint that the number of distinct integers in A[i...j] is less than or equal to K.
Formally, you are to compute:
$$\max_{0 \le i \le j < n} \{ (j - i + 1) \;:\; \#\{a_k \;|\; i \le k \le j\} \le K \} $$Note that if K = 0 or the array is empty, the answer should be 0
.
inputFormat
The input is given via stdin and consists of two lines:
- The first line contains two integers n and K where n is the number of elements in the array and K is the maximum allowed distinct integers.
- The second line contains n space-separated integers representing the array elements.
outputFormat
Output a single integer to stdout representing the maximum length of a contiguous subarray that contains at most K distinct integers.
## sample5 2
1 2 1 2 3
4