Find the length of the longest subsequence where the maximum and minimum values differ by exactly 1.
Given an integer array, find the length of the longest harmonious subsequence.
A subsequence is harmonious if the difference between its largest and smallest values is exactly 1. The elements of the subsequence do not need to be contiguous, but they must come from the original array.
Your task is to return the maximum possible length of such a subsequence. If no harmonious subsequence exists, return 0.
nums.nums[i] is an integer element of the array.Example 1
Input
nums = [1,3,2,2,5,2,3,7]
Output
5
Explanation
The longest harmonious subsequence is [3,2,2,2,3], which contains only 2 and 3, and the difference between max and min is 1.
Example 2
Input
nums = [1,1,1,1]
Output
0
Explanation
All elements are the same, so there is no subsequence whose max and min differ by exactly 1.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.