#K35552. Longest Contiguous Subarray with At Most Two Distinct Integers

    ID: 25556 Type: Default 1000ms 256MiB

Longest Contiguous Subarray with At Most Two Distinct Integers

Longest Contiguous Subarray with At Most Two Distinct Integers

You are given an array of integers. Your task is to find the length of the longest contiguous subarray that contains at most two distinct integers. Formally, if the array is \(A = [a_1, a_2, \dots, a_n]\), you need to find the maximum value of \(j - i + 1\) for which the subarray \(A[i \dots j]\) contains at most two distinct values.

Example:

Input: [1, 2, 1, 2, 3, 4, 3]
Output: 4

In the above example, one of the longest subarrays that satisfies the condition is [1, 2, 1, 2].

This problem requires efficient sliding window techniques to meet the input constraints.

inputFormat

The first line of input contains a single integer \(T\) denoting the number of test cases. Each test case is described as follows:

  • The first line contains an integer \(n\), the number of elements in the array.
  • The second line contains \(n\) space-separated integers representing the elements of the array.

For example:

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

outputFormat

For each test case, output a single line containing the maximum length of a contiguous subarray that contains at most two distinct integers.

For the sample input above, the output should be:

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

</p>