Longest Harmonious Subsequence

Question

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.

Example 1:

Input: [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].

Note: The length of the input array will not exceed 20,000.

Tags

  • Array

Thought

Two approaches:

  • With hash table
  • Without hash table

For the first algorithm, use the hash table to store the counter of each number in the array.

For the second algorithm, sort the array directly and traversal through the sorted array for finding the maximum length.

Code

With hash table

class Solution(object):
    def findLHS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 0:
            return 0
        counter = dict()
        for num in nums:
            if num not in counter:
                counter[num] = 1
            else:
                counter[num] += 1
        maxLength = 0
        keys = counter.keys()
        keys.sort()
        for i in xrange(1, len(keys)):
            prevNum = keys[i - 1]
            currentNum = keys[i]
            if currentNum - prevNum == 1:
                maxLength = max(maxLength, counter[prevNum] + counter[currentNum])
        return maxLength

Without hash table

class Solution(object):
    def findLHS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) <= 1:
            return 0
        nums.sort()
        maxLength = 0
        index = 1
        currentNumber = nums[0]
        currentLength = 1
        prevNumber = None
        prevLength = 0
        while index < len(nums):
            if nums[index] == currentNumber:
                currentLength += 1
            else:
                if prevNumber is not None and currentNumber - prevNumber == 1:
                    maxLength = max(maxLength, currentLength + prevLength)
                prevNumber, prevLength = currentNumber, currentLength
                currentNumber, currentLength = nums[index], 1
            index += 1
        if prevNumber is not None and currentNumber - prevNumber == 1:
            maxLength = max(maxLength, currentLength + prevLength)
        return maxLength

results matching ""

    No results matching ""