#C14296. Longest Subarray with At Most K Distinct Integers

    ID: 43929 Type: Default 1000ms 256MiB

Longest Subarray with At Most K Distinct Integers

Longest Subarray with At Most K Distinct Integers

You are given an array 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.

Formally, for a given array \(A = [a_1, a_2, \dots, a_n]\) and an integer \(k\), find the maximum length \(L\) such that there exists indices \(i\) and \(j\) with \(1 \le i \le j \le n\) satisfying

[ |{ a_i, a_{i+1}, \dots, a_j }| \le k, ]

where \(|\{ a_i, a_{i+1}, \dots, a_j \}|\) denotes the number of distinct elements in the subarray \(A[i \dots j]\). If no valid subarray exists, print 0.

Note: If k is 0, then no subarray containing any element is valid, and the answer is 0.

inputFormat

The input is given from stdin and consists of two lines:

  • The first line contains two space-separated integers \(n\) and \(k\), where \(n\) is the number of elements in the array and \(k\) is the maximum number of distinct integers allowed in a subarray.
  • The second line contains \(n\) space-separated integers representing the elements of the array.

If \(n = 0\), the second line will be empty.

outputFormat

Print a single integer to stdout representing the length of the longest contiguous subarray that contains at most \(k\) distinct integers.

## sample
5 2
1 2 1 2 3
4