Description
We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1. Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences.
Examples
Input:
nums = [1,3,2,2,5,2,3,7]Output:
5Explanation:
[3,2,2,2,3] is harmonious with length 5.
Input:
nums = [1,1,1,1]Output:
0Explanation:
All elements are the same (1). A harmonious array requires exactly two distinct values with difference 1. Since there's only one unique value, no harmonious subsequence exists, so the length is 0.
Input:
nums = [4,5,4,6,5,5,4]Output:
6Explanation:
Harmonious subsequences can be formed with pairs (4,5) or (5,6). The pair (4,5) appears as [4,5,4,5,5,4] with length 6, while (5,6) appears as [5,6,5,5] with length 4. The longest harmonious subsequence has length 6.
Constraints
- •
1 ≤ nums.length ≤ 2 * 10^4 - •
-10^9 ≤ nums[i] ≤ 10^9