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
Longest Harmonious SubsequenceInput:13225Harmonious subsequences:[1,2]: length 2[3,2,2]: length 3max(3,2,2) - min(3,2,2) = 3 - 2 = 1 ✓Output: 3Longest subsequence with exactly 1 difference
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
Asked in
Amazon 15 Facebook 8
28.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen