Skip to content

594. Longest Harmonious Subsequence #1870

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We need to find the length of the longest harmonious subsequence in an array. A harmonious subsequence is defined as a subsequence where the difference between the maximum and minimum elements is exactly 1.

Approach

  1. Frequency Count: First, we count the frequency of each number in the array using a hash table (or a frequency map). This helps us quickly access how many times each number appears in the array.
  2. Check Consecutive Numbers: For each unique number in the frequency map, we check if the next consecutive number (i.e., num + 1) exists in the map. If it does, the length of the harmonious subsequence formed by these two numbers is the sum of their frequencies.
  3. Track Maximum Length: We …

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@basharul-siddike
Comment options

@mah-shamim
Comment options

mah-shamim Jun 30, 2025
Maintainer Author

Answer selected by basharul-siddike
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested easy Difficulty
2 participants