Longest Harmonious Subsequence

We define a harmonious array as an array 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 possible subsequences. A subsequence is derived from the array by deleting some or no elements without changing the order of the remaining elements.

30:00

Longest Harmonious Subsequence
easy
Free written solution
Topics
Companies

We define a harmonious array as an array 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 possible subsequences.

A subsequence is derived from the array by deleting some or no elements without changing the order of the remaining elements.

Example 1:
Input: {"nums":[1,3,2,2,5,2,3,7]}
Output: 5
Constraints:
  • 1≤nums.length≤2×1041 \leq \text{nums.length} \leq 2 \times 10^4

  • −109≤nums[i]≤109-10^9 \leq \text{nums}[i] \leq 10^9

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,3,2,2,5,2,3,7]}

A subsequence may pick any elements, so order does not matter: only how many copies of v and v + 1 we can take.

input (original order)

1
3
2
2
5
2
3
7

0

1

2

3

4

5

6

7

window size

-

max - min

-

best

0

Variables
VariableValue
n8
DepthFunction Call
Stack empty
0/26