#K35102. Longest Subarray with At Most Two Distinct Values
Longest Subarray with At Most Two Distinct Values
Longest Subarray with At Most Two Distinct Values
You are given an array of integers. Your task is to find the length of the longest contiguous subarray that contains no more than two distinct values. In addition, if the subarray contains exactly two distinct values, then the absolute difference between them must be no more than \(1\), i.e. \(|a - b| \le 1\) where \(a\) and \(b\) are the two distinct numbers.
Example 1: For the array [1, 2, 1, 2, 3], the longest valid subarray is [1, 2, 1, 2] with a length of 4.
Example 2: For the array [4, 4, 4, 4], the entire array is valid with a length of 4.
Note: A subarray is a contiguous portion of the array.
inputFormat
The input is given via standard input (stdin) and has the following format:
The first line contains an integer \(n\) \( (1 \le n \le 10^5)\), representing the number of elements in the array. The second line contains \(n\) space-separated integers representing the elements of the array.
It is guaranteed that the array elements are integers.
outputFormat
Output a single integer via standard output (stdout), representing the length of the longest contiguous subarray that satisfies the condition.
## sample5
1 2 1 2 3
4