594. Longest Harmonious Subsequence
We define a harmounious array as 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.
Example 1:
Input: [1,3,2,2,5,2,3,7] Output: 5 Explanation: The longest harmonious subsequence is [3,2,2,2,3].
Python Brute Force:
class Solution:
def findLHS(self, nums: List[int]) -> int:
nums.sort()
res=0
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[j] == nums[i]:
continue
elif nums[i] + 1 == nums[j]:
res=max(res,j-i+1)
return res
TLE.
Using HashTable:
class Solution:
def findLHS(self, nums: List[int]) -> int:
d={}
for i in nums:
d[i] = d.get(i,0) + 1
res=0
for k in d:
if k+1 in d:
res=max(res,d[k]+d[k+1])
return res