#K74037. 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
You are given an array of integers and an integer \(K\). Your task is to find the maximum length of a contiguous subarray that contains at most \(K\) distinct integers.
A subarray is a contiguous segment of the array. Formally, given an array \(A\) of length \(n\), you need to find the largest integer \(L\) such that there exists indices \(i\) and \(j\) with \(0 \leq i \leq j < n\) and \(j - i + 1 = L\), and the number of distinct integers in the subarray \(A[i\dots j]\) is less than or equal to \(K\).
Example:
- Input: A = [1, 2, 1, 2, 3], \(K = 2\)
- Output: 4
- Explanation: The subarray [1, 2, 1, 2] has 2 distinct integers and is of maximum possible length.
Note: If \(K = 0\), then the result should be 0 because no subarray can have 0 distinct integers.
inputFormat
The input is read from standard input (stdin) and has the following format:
n K a1 a2 ... an
Where:
- \(n\) is the number of elements in the array.
- \(K\) is the maximum number of distinct integers allowed in the subarray.
- ai are the elements of the array.
outputFormat
Output a single integer on a line by itself representing the maximum length of a contiguous subarray that contains at most \(K\) distinct integers. The output should be sent to standard output (stdout).
## sample5 2
1 2 1 2 3
4