Longest Harmonious Subsequence - Problem
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.
Note: A subsequence is derived from an array by deleting some or no elements without changing the order of the remaining elements.
Input & Output
Example 1 — Basic Harmonious Array
$
Input:
nums = [1,3,2,2,5,2,3,7]
›
Output:
5
💡 Note:
The longest harmonious subsequence is [3,2,2,2,3] with length 5. It contains numbers 2 and 3, and 3-2=1.
Example 2 — No Harmonious Subsequence
$
Input:
nums = [1,2,3,4]
›
Output:
2
💡 Note:
Multiple harmonious subsequences exist: [1,2], [2,3], [3,4], each with length 2. Return the maximum length which is 2.
Example 3 — All Same Numbers
$
Input:
nums = [1,1,1,1]
›
Output:
0
💡 Note:
All numbers are the same, so max-min=0, not 1. No harmonious subsequence exists.
Constraints
- 1 ≤ nums.length ≤ 2 × 104
- -109 ≤ nums[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Array with various numbers
2
Find Harmonious
Look for subsequences where max - min = 1
3
Return Length
Length of longest valid subsequence
Key Takeaway
🎯 Key Insight: Only consecutive integers can form harmonious subsequences, so count frequencies and pair adjacent numbers
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code