#C8996. Longest Subarray with K Distinct Integers
Longest Subarray with K Distinct Integers
Longest Subarray with K Distinct Integers
You are given an array A of n integers and an integer k. Your task is to find the length of the longest contiguous subarray that contains at most k distinct integers. In other words, if we denote by \(D(x)\) the number of distinct integers in subarray x, you need to find the maximum length \(L\) such that there exists a subarray with L elements and \(D(x) \le k\).
Example: For A = [1, 2, 1, 2, 3, 4, 1]
and k = 2
, the longest subarray with at most 2 distinct integers is [1, 2, 1, 2]
, which has a length of 4.
This problem can be efficiently solved using the sliding window technique.
inputFormat
The first line contains two integers n
and k
(the size of the array and the maximum number of distinct integers allowed, respectively). The second line contains n
integers representing the array A
.
Constraints:
- 1 ≤ n ≤ 105
- 0 ≤ k ≤ n
- The elements of
A
are integers.
outputFormat
Output a single integer representing the length of the longest subarray with at most k
distinct integers.
7 2
1 2 1 2 3 4 1
4
</p>