Longest Harmonious Subsequence

We define a harmonious array as one where the difference between its maximum value and its minimum value is exactly 1. Given an integer array *nums*, return *the length of its longest harmonious subsequence among all its subsequences* (not necessarily contiguous). A subsequence is derived by deleting some elements without changing the order of the remaining elements.

Input Format

nums = [array of integers]

Output Format

integer (length of longest harmonious subsequence)

Constraints

  • 1 <= nums.length <= 2 * 10^4; -10^9 <= nums[i] <= 10^9

Examples

Example 1:

Input:

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

Output:

5

Explanation:

The longest harmonious subsequence is [3,2,2,2,3], which has length 5.

Example 2:

Input:

nums = [1,2,3,4]

Output:

2

Explanation:

The longest harmonious subsequence can be [2,3] or [3,4].

Loading...
Longest Harmonious Subsequence - Hashing