We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly
Given an integer array
nums, 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.
1 <= nums.length <= 2 * 10^4
-10^9 <= nums[i] <= 10^9
- Level: Easy
- Acceptance: 51.2%
For this question, I used a map just for the fun of it. Using an object would work as well. The first
for loop will loop through the array and store each number as a key along with the number of times they are repeated. The second
for loop will check for a number in the array and a number that is one greater than it. If both numbers can be found in the map, the algorithm checks to see if the sum of their number of occurrences exceed
max. If the sum exceed
max, replace it with the sum else, continue with looping through the array.