319. Longest Harmonious Subsequence
Easy
Adjacent Frequency Pair
Hashing
Problem
A harmonious subsequence is a subsequence in which the difference between its maximum and minimum values is exactly 1. Given an integer array nums, return the length of its longest harmonious subsequence.
Examples
Example 1
Input: [1,3,2,2,5,2,3,7]
Output: 5
Example 2
Input: [1,2,3,4]
Output: 2
Example 3
Input: [1,1,1,1]
Output: 0
Constraints
� 1 <= nums.length <= 20000
� -1000000000 <= nums[i] <= 1000000000
Hints
?? Count the frequency of every distinct value.
?? For each value x, check whether x + 1 exists.
?? If it exists, the two complete frequency groups form a harmonious subsequence.
Expected Complexity
Time: O(n)
Space: O(n)
Follow-up
Can you solve it in a single pass while maintaining frequencies?
Practice Notes
Attempts: 0
Time spent: 0min
Hints used: 0
JavaScript
00:00
Loading...
Case 1
Case 2
Case 3
Input
[1,3,2,2,5,2,3,7]Expected
5