# 594. Longest Harmonious Subsequence

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.

``````class Solution {
public:
int findLHS(vector<int>& nums) {
if (nums.empty()) return 0;
int res = 0;
map<int, int> m;
for (int num : nums) ++m[num];
for (auto it = next(m.begin()); it != m.end(); ++it) {
auto pre = prev(it);
if (it->first == pre->first + 1) {
res = max(res, it->second + pre->second);
}
}
return res;
}
};
``````

``````class Solution {
public:
int findLHS(vector<int>& nums) {
int res = 0;
unordered_map<int, int> m;
for (int num : nums) ++m[num];
for (auto a : m) {
if (m.count(a.first + 1)) {
res = max(res, m[a.first] + m[a.first + 1]);
}
}
return res;
}
};
``````

``````class Solution {
public:
int findLHS(vector<int>& nums) {
int res = 0;
unordered_map<int, int> m;
for (int num : nums) {
++m[num];
if (m.count(num + 1)) {
res = max(res, m[num] + m[num + 1]);
}
if (m.count(num - 1)) {
res = max(res, m[num] + m[num - 1]);
}
}
return res;
}
};
``````

``````class Solution {
public:
int findLHS(vector<int>& nums) {
int res = 0, start = 0, new_start = 0;
sort(nums.begin(), nums.end());
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] - nums[start] > 1) start = new_start;
if (nums[i] != nums[i - 1]) new_start = i;
if (nums[i] - nums[start] == 1) res = max(res, i - start + 1);
}
return res;
}
};
``````

https://leetcode.com/problems/longest-harmonious-subsequence/

https://leetcode.com/problems/longest-harmonious-subsequence/discuss/103497/Simple-Java-HashMap-Solution

https://leetcode.com/problems/longest-harmonious-subsequence/discuss/103499/Three-C%2B%2B-Solution-run-time-with-explanation

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation