Leetcode Problem 594. Longest Harmonious Subsequence
594. Longest Harmonious Subsequence
Leetcode Solutions
Using HashMap
Initialize a HashMap to store the frequency of each element in the array.
Iterate over the array, populating the HashMap with the count of each number.
Initialize a variable max_length to 0 to keep track of the maximum length of a harmonious subsequence found so far.
Iterate over the keys of the HashMap.
a. For each key, check if the key plus one exists in the HashMap.
b. If it does, calculate the length of the harmonious subsequence as the sum of the counts of the key and the key plus one.
c. Update max_length with the maximum of its current value and the calculated length.
Return max_length as the length of the longest harmonious subsequence.