#K61722. Longest Subarray with Difference at Most One
Longest Subarray with Difference at Most One
Longest Subarray with Difference at Most One
Given an array of integers, find the length of the longest subarray (not necessarily contiguous in the original order, but considered as a subset of the array) such that the absolute difference between any two elements is at most 1. In other words, if the subarray is denoted by S, then for every pair of elements a and b in S, it must hold that \(|a - b| \le 1\).
Note: An empty array should return 0. This problem can be solved using a frequency map to count the occurrences of each number and then checking the sums of counts for adjacent numbers (i.e. numbers with difference 1).
inputFormat
The first line contains an integer n, the number of elements in the array. The second line contains n space-separated integers representing the array elements.
outputFormat
Output a single integer representing the length of the longest subarray where the absolute difference between any two elements is at most 1.
## sample6
1 2 2 3 1 2
5