#K81087. Longest Subarray with M Distinct Integers
Longest Subarray with M Distinct Integers
Longest Subarray with M Distinct Integers
You are given an array of positive integers and an integer M. Your task is to find the length of the longest contiguous subarray that contains at most M distinct integers. Formally, given an array A of size N, find the maximum length L such that for some indices i and j (with 0 ≤ i ≤ j < N), the subarray A[i..j] satisfies ( |{ A[k] : i \le k \le j }| \le M ). If no valid subarray exists, output 0.
This problem can be efficiently solved using the sliding window (or two pointers) technique. As you process the array, maintain a window that satisfies the constraint and update the maximum window length.
inputFormat
The first line contains two integers N and M, where N is the number of elements in the array and M is the maximum number of distinct integers allowed in a subarray. The second line contains N space-separated positive integers representing the array.
outputFormat
Output a single integer representing the length of the longest contiguous subarray that contains at most M distinct integers.## sample
7 2
1 2 1 2 3 4 5
4