Longest Harmonious Subsequence

Problem Id: 594 Difficulty: Easy


Intuition

Solution


class Solution:
    def findLHS(self, nums: List[int]) -> int:
        count = {}
        for num in nums:
            if num not in count:
                count[num] = 0
            count[num] += 1

        ans = 0
        for k in count:
            if k + 1 not in count:
                continue
            ans = max(ans, count[k] + count[k + 1])
        return ans