#C10025. Longest Subarray with Exactly K Distinct Numbers

    ID: 39185 Type: Default 1000ms 256MiB

Longest Subarray with Exactly K Distinct Numbers

Longest Subarray with Exactly K Distinct Numbers

You are given a sequence of integers and an integer k. Your task is to find the length of the longest contiguous subarray that contains exactly k distinct integers.

Note: If no such subarray exists, output 0.

Example:
For the array [1, 2, 1, 2, 3, 2, 2] and k = 2, the longest contiguous subarray containing exactly 2 distinct numbers is [1, 2, 1, 2] with length 4.

This problem requires handling multiple test cases. The input is given from stdin and the output should be printed to stdout.

inputFormat

The input begins with an integer T, representing the number of test cases.

For each test case, the input consists of three lines:

  1. An integer n, representing the length of the array.
  2. n space-separated integers representing the array elements.
  3. An integer k, representing the number of distinct integers required in the subarray.

    For example:
    2\n7\n1 2 1 2 3 2 2\n2\n5\n5 5 5 1 1\n1

outputFormat

For each test case, print a single integer on a new line: the maximum length of a contiguous subarray that contains exactly k distinct integers. If no such subarray exists, print 0.## sample

2
7
1 2 1 2 3 2 2
2
5
5 5 5 1 1
4

3

</p>