A harmonious array is a special type of array where the difference between its maximum and minimum values is exactly 1. This creates a balanced, "harmonious" relationship between the elements.
Given an integer array nums, your task is to find the length of the longest harmonious subsequence among all possible subsequences.
A subsequence is derived from an array by deleting some or no elements without changing the order of the remaining elements. However, for this problem, order doesn't matter since we only care about the min/max difference.
Example: In array [1,3,2,2,5,2,3,7], one harmonious subsequence could be [3,2,2,2,3] (min=2, max=3, difference=1), which has length 5.
Goal: Return the length of the longest possible harmonious subsequence, or 0 if no harmonious subsequence exists.
Input & Output
Visualization
Time & Space Complexity
Single pass through array with O(1) hash operations
Hash map stores at most n unique elements with their frequencies
Constraints
- 1 โค nums.length โค 2 ร 104
- -109 โค nums[i] โค 109
- The array can contain duplicate elements
- Subsequence order doesn't matter (we only care about min/max difference)