#K91277. Maximum Length of a Contiguous Subarray with At Most Two Distinct Integers
Maximum Length of a Contiguous Subarray with At Most Two Distinct Integers
Maximum Length of a Contiguous Subarray with At Most Two Distinct Integers
Given an array of integers, your task is to compute the maximum length of a contiguous subarray that contains at most two distinct integers.
You are given an integer n representing the number of elements in the array, followed by n space‐separated integers. Formally, you need to find the maximum L such that there exists indices \(i\) and \(j\) with \(0 \le i \le j < n\) and
[ |{a_i, a_{i+1}, \ldots, a_j}| \le 2, ]
where \(|\cdot|\) denotes the size of a set. The answer is the maximum \(j - i + 1\) over all valid contiguous segments.
Example:
Input: 2 6 1 2 1 3 4 2 5 1 2 2 2 2</p>Output: 3 5
The first test case has a subarray [1, 2, 1] with length 3, and the second test case itself is the longest subarray because all elements are within two distinct values.
inputFormat
The input is given in stdin and consists of multiple test cases.
The first line contains a single integer t
denoting the number of test cases. For each test case, the first line contains an integer n
denoting the size of the array. The second line contains n
space-separated integers representing the array elements.
Input Format:
t n a1 a2 ... an ... (repeated for each test case)
outputFormat
For each test case, output one integer on a separate line representing the maximum length of a contiguous subarray that contains at most two distinct integers. The answer for each test case should be printed in order on stdout.
## sample2
6
1 2 1 3 4 2
5
1 2 2 2 2
3
5
</p>