A harmonious subsequence has elements whose max and min differ by exactly 1. By counting the frequency of each number, we can efficiently check for pairs of numbers that differ by 1 and sum their counts for the answer.
classSolution {
public:int findLHS(vector<int>& nums) {
unordered_map<int, int> cnt;
for (int x : nums) cnt[x]++;
int ans =0;
for (auto& [k, v] : cnt) {
if (cnt.count(k+1)) ans = max(ans, v + cnt[k+1]);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
funcfindLHS(nums []int) int {
cnt:=map[int]int{}
for_, x:=rangenums {
cnt[x]++ }
ans:=0fork, v:=rangecnt {
ifc, ok:=cnt[k+1]; ok {
ifv+c > ans {
ans = v+c }
}
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
publicintfindLHS(int[] nums) {
Map<Integer, Integer> cnt =new HashMap<>();
for (int x : nums) cnt.put(x, cnt.getOrDefault(x, 0) + 1);
int ans = 0;
for (int k : cnt.keySet()) {
if (cnt.containsKey(k+1)) ans = Math.max(ans, cnt.get(k) + cnt.get(k+1));
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funfindLHS(nums: IntArray): Int {
val cnt = mutableMapOf<Int, Int>()
for (x in nums) cnt[x] = cnt.getOrDefault(x, 0) + 1var ans = 0for ((k, v) in cnt) {
if (cnt.containsKey(k+1)) ans = maxOf(ans, v + cnt[k+1]!!)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
classSolution:
deffindLHS(self, nums: list[int]) -> int:
from collections import Counter
cnt = Counter(nums)
ans =0for k in cnt:
if k+1in cnt:
ans = max(ans, cnt[k] + cnt[k+1])
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnfind_lhs(nums: Vec<i32>) -> i32 {
use std::collections::HashMap;
letmut cnt = HashMap::new();
for&x in&nums {
*cnt.entry(x).or_insert(0) +=1;
}
letmut ans =0;
for (&k, &v) in&cnt {
iflet Some(&c) = cnt.get(&(k+1)) {
ans = ans.max(v + c);
}
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
findLHS(nums: number[]):number {
constcnt=newMap<number, number>();
for (constxofnums) cnt.set(x, (cnt.get(x) ||0) +1);
letans=0;
for (const [k, v] ofcnt.entries()) {
if (cnt.has(k+1)) ans= Math.max(ans, v+cnt.get(k+1)!);
}
returnans;
}
}