#C9584. Longest Subarray with At Most K Distinct Elements

    ID: 53693 Type: Default 1000ms 256MiB

Longest Subarray with At Most K Distinct Elements

Longest Subarray with At Most K Distinct Elements

You are given an array of integers and an integer K. Your task is to compute the length of the longest contiguous subarray that contains at most K distinct elements.

In other words, let the array be represented as \( A[0 \ldots n-1] \) and let \( K \) be a non-negative integer. You need to find the maximum length of a subarray \( A[i \ldots j] \) such that the number of distinct elements in this subarray is at most \( K \). Formally, if \( D(i,j) \) represents the number of distinct elements in \( A[i \ldots j] \), then you must maximize \( j - i + 1 \) subject to \( D(i,j) \le K \).

If K is 0 or the array is empty, the answer is 0.

inputFormat

The input is read from standard input and consists of two lines:

  • The first line contains two integers n and K, where n is the number of elements in the array.
  • The second line contains n space-separated integers representing the elements of the array.

outputFormat

Output a single integer: the length of the longest subarray that contains at most K distinct elements.

## sample
5 2
1 2 1 2 3
4