Longest Harmonious Subsequence

easy hash map counter

Problem

Return the longest subsequence whose max value − min value is exactly 1.

Inputnums = [1,3,2,2,5,2,3,7]
Output5
Values 2 and 3 — count 3 + 2 = 5.

def find_lhs(nums):
    from collections import Counter
    c = Counter(nums)
    return max((c[x] + c[x+1] for x in c if x+1 in c), default=0)
function findLHS(nums) {
  const c = new Map();
  nums.forEach(x => c.set(x, (c.get(x)||0)+1));
  let best = 0;
  for (const [x, v] of c) if (c.has(x+1)) best = Math.max(best, v + c.get(x+1));
  return best;
}
int findLHS(int[] nums) {
    Map c = new HashMap<>();
    for (int x : nums) c.merge(x, 1, Integer::sum);
    int best = 0;
    for (var e : c.entrySet()) if (c.containsKey(e.getKey()+1)) best = Math.max(best, e.getValue() + c.get(e.getKey()+1));
    return best;
}
int findLHS(vector& nums) {
    unordered_map c;
    for (int x : nums) c[x]++;
    int best = 0;
    for (auto& [k, v] : c) if (c.count(k+1)) best = max(best, v + c[k+1]);
    return best;
}
Time: O(n) Space: O(n)