#K38472. Longest Subarray with At Most Two Distinct Integers
Longest Subarray with At Most Two Distinct Integers
Longest 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, given an array ( A ) of length ( n ), find the maximum value of ( L = j - i + 1 ) where the subarray ( A[i , ... , j] ) contains no more than two distinct integers.
For example, if ( A = [1, 2, 1] ), the answer is 3 because the entire array contains two distinct elements. Similarly, if ( A = [1, 2, 3, 2, 2] ), the longest valid subarray is ( [2, 3, 2, 2] ) with length 4.
Implement an efficient algorithm to solve this problem.
inputFormat
Input is read from standard input (stdin). The first line contains a single integer ( n ) representing the number of elements in the array. The second line contains ( n ) space-separated integers, which are the elements of the array.
outputFormat
Output to standard output (stdout) a single integer denoting the length of the longest contiguous subarray with at most two distinct integers.## sample
3
1 2 1
3