#K12121. Longest Subarray with Two Distinct Integers
Longest Subarray with Two Distinct Integers
Longest Subarray with Two Distinct Integers
Given an array of integers, your task is to find the length of the longest contiguous subarray that contains at most two distinct integers. In other words, define a subarray as a contiguous part of the given array. Let the subarray be represented as \(A[l..r]\). You need to ensure that the number of distinct integers in \(A[l..r]\) is not more than 2. The answer is the maximum possible length of such a subarray.
Input Format: The first line contains an integer \(n\), denoting the number of elements in the array. The second line contains \(n\) integers separated by spaces.
Output Format: Print a single integer which represents the length of the longest contiguous subarray that contains at most two distinct integers.
Example:
Input: 9 1 2 1 2 3 4 5 1 2</p>Output: 4
Note: \(n\) can be as large as millions, so efficiency is crucial. Use an appropriate algorithm to achieve an optimal solution.
inputFormat
The input is read from stdin and consists of multiple lines. The first line has an integer \(n\) denoting the number of elements in the array. The second line contains \(n\) integers separated by a space.
For example:
9 1 2 1 2 3 4 5 1 2
outputFormat
The output is written to stdout and is a single integer that denotes the length of the longest contiguous subarray with at most two distinct integers.
For example, the output corresponding to the example above is:
4## sample
9
1 2 1 2 3 4 5 1 2
4
</p>