Skip to content

Latest commit

 

History

History
 
 

594. Longest Harmonious Subsequence

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.

Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.

Example 1:

Input: [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].

Note: The length of the input array will not exceed 20,000.

Companies:
LiveRamp

Related Topics:
Hash Table

Solution 1.

// OJ: https://leetcode.com/problems/longest-harmonious-subsequence/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
    int findLHS(vector<int>& nums) {
        unordered_map<int, int> cnts;
        int ans = 0;
        for (int n : nums) cnts[n]++;
        for (auto &p : cnts) {
            if (cnts.find(p.first + 1) == cnts.end()) continue;
            ans = max(ans, p.second + cnts[p.first + 1]);
        }
        return ans;
    }
};