[LeetCode] Longest Harmonious Subsequence

594. Longest Harmonious Subsequence

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

Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int findLHS(vector<int>& nums) {
unordered_map<int,int> freq;
for(auto& n : nums) freq[n]++;
int res = 0;
for(auto& [k,v] : freq) {
if(freq.count(k+1)) res = max(res, v + freq[k+1]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/06/30/PS/LeetCode/longest-harmonious-subsequence/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.