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 )
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)
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.