#C11758. Longest Subarray with Two Distinct Numbers
Longest Subarray with Two Distinct Numbers
Longest Subarray with Two Distinct Numbers
You are given a list of integers. Your task is to find the longest contiguous subarray that contains at most two distinct numbers. In other words, if the subarray contains more than two different integers, it is not a valid candidate. If there are multiple subarrays of the same maximum length, choose the one with the smallest starting index.
The input is provided via standard input, and the answer should be printed via standard output as a single line of space-separated numbers. If the input list is empty, print nothing.
Mathematically, if \(A = [a_1, a_2, \dots, a_n]\), you need to find indices \(i, j\) (with \(1 \leq i \leq j \leq n\)) such that the contiguous subarray \(A[i \dots j]\) contains at most two distinct numbers and \(j-i+1\) is maximized.
inputFormat
The first line contains an integer \(n\) representing the number of elements in the list. The second line contains \(n\) space-separated integers.
outputFormat
Output the longest contiguous subarray (as a sequence of space-separated integers) that contains at most two distinct numbers. If there is no valid subarray (i.e. when \(n = 0\)), output an empty line.
## sample5
1 2 1 2 3
1 2 1 2