# 594.Longest Harmonious Subsequence

**594.Longest Harmonious Subsequence**

难度:Easy

> We define a harmounious array as 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.

采用hashMap统计每个数出现的次数，然后比较相邻两个数出现次数之和，求出最大值即可。

```
class Solution {
public:
    int findLHS(vector<int>& nums) {
        if(nums.empty()  || nums.size()==1) return 0;
        int res=0;
        unordered_map<int,int> cnt;
        for(int i=0;i<nums.size();i++)
            ++cnt[nums[i]];
        cout<<cnt.size()<<endl;
        for(auto start=cnt.begin();start!=cnt.end();start++)
        {
            if(cnt.count(start->first+1))
            res=max(res,start->second+cnt[start->first+1]);
            if(cnt.count(start->first-1))
            res=max(res,start->second+cnt[start->first-1]);
          //  cout<< res<<endl;
        }
        return res;
    }
};
```

> 执行用时 :116 ms, 在所有 C++ 提交中击败了80.28%的用户\
> 内存消耗 :19.6 MB, 在所有 C++ 提交中击败了76.63%的用户


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/594.longest_harmonious_subsequence.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
