dsa · easy

Longest Harmonious Subsequence

A subsequence is **harmonious** when the difference between its largest and smallest values is **exactly** 1. Values need not be adjacent in nums; you may skip entries. The subsequence may not be empty of either extreme — a run of equal values has difference 0 and is not harmonious.

Arguments

Return the length of the longest harmonious subsequence of nums (or 0 if none exists).

Example

nums = [1, 3, 2, 2, 5, 2, 3, 7].

The values 3, 2, 2, 2, 3 use only 2 and 3 (difference 1) and have length 5. No longer mixed pair exists, so the answer is 5.

nums = [1, 2, 3, 4]2 (any neighbouring pair).

nums = [1, 1, 1, 1]0 (no value one away from 1).

Constraints

1 <= nums.length <= 4*10^4 -10^9 <= nums[i] <= 10^9 Hidden tests include near-max size for this bound; a slower-than-intended solution TLEs.

Examples

Example 1

Input:
[1, 3, 2, 2, 5, 2, 3, 7]

Expected:
5

Example 2

Input:
[1, 2, 3, 4]

Expected:
2

Example 3

Input:
[1, 1, 1, 1]

Expected:
0

Open in the Dojo editor