Longest Harmonious Subsequence

Easy
1
30.0% Acceptance

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 be 5.

  • For nums = [1,2,3,4], the longest harmonious subsequence is [1, 2] or [3, 4], and the output should be 2.

  • For nums = [1,1,1,1], there is no harmonious subsequence, and the output should be 0.

Constraints:

  • 1 <= nums.length <= 2 * 104
  • -109 <= nums[i] <= 109

Challenges

  1. Export a function findLHS which takes an argument nums and returns the length of its longest harmonious subsequence. Example: findLHS([1,3,2,2,5,2,3,7]) should return 5.

  2. 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.