https://leetcode.com/problems/longest-harmonious-subsequence

In this problem we need to find the biggest group of elements, such that they values are adjacent numbers. Note, that order of numbers does not matter. Let us look at the example [1, 1, 1, 3, 3, 4, 5, 5, 5, 7, 8, 10]. Then we have the following groups with adjacent elements: [3, 3, 4], [4, 5, 5, 5] and [7, 8]. What we need to do is to use Counter to count how many times we have each element, then check if we have element which is bigger by one and update our answer if needed.

Denote C = Counter(nums), then what we can do is to iterate for n in C, check if C[n+1] != 0, that is we have next element and update C[n] + C[n+1]: number of elements in this group.

Complexity: time and space complexity is O(n): we create counter and iterate over it once.

PS: if you know a way to make it oneliner, please let me know =) I tried to use (C := Counter(nums)), but it is not working for some reason.

class Solution:
    def findLHS(self, nums):
        C = Counter(nums)
        return max((C[n] + C[n+1])*(C[n+1] != 0) for n in C)

If you like the solution, you can upvote it on leetcode discussion section: Problem 0594