- Longest Harmonious Subsequence
We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.
Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.
# version 1
def findLHS(self, A):
count = collections.Counter(A)
ans = 0
for x in count:
if x+1 in count:
ans = max(ans, count[x] + count[x+1])
return ans
# version 2
def findLHS(self, A):
count = {}
# more straightforward way to count
for x in A:
count[x] = count.get(x, 0) + 1
ans = 0
for x in count:
if x+1 in count:
ans = max(ans, count[x] + count[x+1])
return ans