#K11021. Longest Special Subarray
Longest Special Subarray
Longest Special Subarray
You are given several messages, where each message is represented as an array of integers. For each message, your task is to find the length of the longest contiguous subarray (i.e. a segment) that contains exactly two distinct integers. If no such subarray exists, output 0 for that message.
A subarray of an array A is a contiguous segment of elements. For this problem, a subarray is considered special if it contains exactly two different integers. Formally, for a given array \(A\) the subarray \(A[i \ldots j]\) (with \(0 \le i \le j < n\)) is special if and only if:
[ \text{number of distinct elements in } {A[i], A[i+1], \ldots, A[j]} = 2. ]
If there is no contiguous segment in a message containing exactly two distinct integers, then the answer for that message is 0.
Example:
Input Message 1: [4, 1, 2, 1, 4, 4, 1] The longest special subarray is [1, 2, 1, 4] with length 4.</p>Input Message 2: [1, 1, 1, 1, 1] There is no special subarray so answer is 0.
inputFormat
The input is read from stdin
in the following format:
T n1 a11 a12 ... a1n1 n2 a21 a22 ... a2n2 ... nt at1 at2 ... atnt
Where:
- T is the number of messages (test cases).
- For each message, the first line contains an integer n representing the length of the message.
- The following line contains n integers separated by spaces representing the message.
outputFormat
For each message, output a single integer on a new line: the length of the longest contiguous subarray that contains exactly two distinct integers. If no such subarray exists, output 0.
## sample2
7
4 1 2 1 4 4 1
5
1 1 1 1 1
4
0
</p>