Longest Harmonious Subsequence
In this lab, you will be working on finding the longest harmonious subsequence within an array of integers. A harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1
. Given an integer array nums
, your task is to return the length of its longest harmonious subsequence among all its possible subsequences.
A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.
Examples:
-
For
nums = [1,3,2,2,5,2,3,7]
, the longest harmonious subsequence is[3,2,2,2,3]
, and the output should be5
. -
For
nums = [1,2,3,4]
, the longest harmonious subsequence is[1, 2]
or[3, 4]
, and the output should be2
. -
For
nums = [1,1,1,1]
, there is no harmonious subsequence, and the output should be0
.
Constraints:
1 <= nums.length <= 2 * 104
-109 <= nums[i] <= 109
Challenges
-
Export a function
findLHS
which takes an argumentnums
and returns the length of its longest harmonious subsequence. Example:findLHS([1,3,2,2,5,2,3,7])
should return5
. -
Test your implementation with varying lengths and values of arrays in
nums
, including arrays with unique elements, arrays with repeating elements, and arrays with negative numbers.