#K14861. Longest Subarray with At Most K Distinct Integers
Longest Subarray with At Most K Distinct Integers
Longest Subarray with At Most K Distinct Integers
You are given an array of integers and an integer k. Your task is to find the length of the longest contiguous subarray that contains at most k distinct integers.
Example: For the array [1, 2, 1, 2, 3, 4, 2] and k = 2, the longest subarray with at most 2 distinct integers is [1, 2, 1, 2] and its length is 4.
Use an efficient approach (e.g., the sliding window technique) to solve the problem.
inputFormat
The first line contains two integers n and k, where n is the number of elements in the array and k is the maximum number of distinct integers allowed. The second line contains n space-separated integers representing the array.
outputFormat
Output a single integer, the length of the longest contiguous subarray that contains at most k distinct integers.## sample
7 2
1 2 1 2 3 4 2
4