#K78192. Longest Subarray with Absolute Difference One
Longest Subarray with Absolute Difference One
Longest Subarray with Absolute Difference One
Given an array of integers, find the length of the longest contiguous subarray such that the absolute difference between any two consecutive elements is exactly 1. Formally, for a subarray a[l...r] (with r ≥ l), it should satisfy that for every index i (l+1 ≤ i ≤ r), \(|a_i - a_{i-1}| = 1\). If no such subarray exists, the answer is 1 (i.e. any single element is considered a valid subarray).
Example:
Input: 6 1 2 2 3 4 4 Output: 3
Explanation: The longest valid contiguous subarray is [2, 3, 4] (or [3, 4, 4] is not valid since |4-4|=0), hence the answer is 3.
inputFormat
The first line contains a single integer n (1 ≤ n ≤ 105), the number of elements in the array. The second line contains n space-separated integers representing the array elements.
outputFormat
Output a single integer - the length of the longest contiguous subarray where every two consecutive elements have an absolute difference of 1.
## sample6
1 2 2 3 4 4
3