Leetcode

Longest Harmonious Subsequence

  • Time:O(n)
  • Space:O(n)

C++

class Solution {
 public:
  int findLHS(vector<int>& nums) {
    int ans = 0;
    unordered_map<int, int> count;

    for (const int num : nums)
      ++count[num];

    for (const auto& [num, freq] : count)
      if (count.count(num + 1))
        ans = max(ans, freq + count[num + 1]);

    return ans;
  }
};

JAVA

class Solution {
  public int findLHS(int[] nums) {
    int ans = 0;
    Map<Integer, Integer> count = new HashMap<>();

    for (final int num : nums)
      count.put(num, count.getOrDefault(num, 0) + 1);

    for (final int num : count.keySet())
      if (count.containsKey(num + 1))
        ans = Math.max(ans, count.get(num) + count.get(num + 1));

    return ans;
  }
}

Python

class Solution:
  def findLHS(self, nums: List[int]) -> int:
    ans = 0
    count = Counter(nums)

    for num, freq in count.items():
      if num + 1 in count:
        ans = max(ans, freq + count[num + 1])

    return ans