Short Python using Counter

  • 3
    class Solution(object):
        def findLHS(self, nums):
            :type nums: List[int]
            :rtype: int
            count = collections.Counter(nums)
            return max([count[x] + count[x+1] for x in count if count[x+1]] or [0])

  • 0

    You can save memory using generator expression, and max() has a default value if input is empty.

    return max((count[x] + count[x+1] for x in count if count[x+1]), default=0)

  • 0

    Yes, you made a good point. The reason I didn't do that is count has at least same order of space complexity compared to the list comprehension thus it won't help much.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.