I am facing a challenge with the following situation: rather than just displaying the length of an array, I want to output the actual array itself.
In this scenario, we are defining a harmonious array as one where the difference between its maximum and minimum values is exactly 1. The task at hand is to find the length of the longest harmonious subsequence within an integer array, focusing on actually identifying the array itself.
For instance: Input: [1,3,2,2,5,2,3,7] Output: 5 Explanation: The longest harmonious subsequence in this case would be [3,2,2,2,3].
I have attempted to solve this issue through coding, but it seems that the values being added into 'vals' are incorrect. Any guidance or correction would be greatly appreciated.
const findLHS = (nums) => {
const hash = new Map()
let vals = []
let min = nums[0], max = nums[0]
for (let num of nums) {
// Flawed logic for finding min and max values
min = min + max === 1 ? Math.min(min, num) : min
max = max - min === 1 ? Math.max(max, num) : max
hash.set(num, (hash.get(num) || 0) + 1)
console.log(max);
}
// Issue in logic below
for (let key of nums) {
if (hash.has(key) === min || hash.has(key) === max) {
vals.push(min) || vals.push(max)
}
}
return vals
}
The test cases, along with my expected results:
console.log(findLHS([1, 3, 2, 2, 5, 2, 3, 7]))//5 [3,2,2,2,3]
console.log(findLHS([1, 2, 3, 4])) //2 [1,2]
console.log(findLHS([1, 2, 2, 1])) //4 [1,2,2,1]