#K48027. Longest Subarray with At Most K Distinct Elements

    ID: 28329 Type: Default 1000ms 256MiB

Longest Subarray with At Most K Distinct Elements

Longest Subarray with At Most K Distinct Elements

Given an array of integers of length \(n\) and an integer \(k\), your task is to find the length of the longest contiguous subarray that contains at most \(k\) distinct integers.

The subarray should be contiguous, and its number of distinct elements must not exceed \(k\). For example, if the input array is [1, 2, 1, 2, 3, 3, 4] with \(k=2\), then the longest subarray satisfying the condition is [1, 2, 1, 2] of length 4.

inputFormat

The input is given via standard input (stdin) in the following format:

<n> <k>
<sequence of n integers separated by spaces>

Where:

  • \(n\) (integer): The number of elements in the sequence.
  • \(k\) (integer): The maximum number of distinct integers allowed in the subarray.
  • The second line contains \(n\) space-separated integers representing the array.

outputFormat

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

## sample
7 2
1 2 1 2 3 3 4
4