Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created June 30, 2025 16:32
Show Gist options
  • Save tatsuyax25/d3d1bd0caaf6bd4e8b052ef1eedf2b5f to your computer and use it in GitHub Desktop.
Save tatsuyax25/d3d1bd0caaf6bd4e8b052ef1eedf2b5f to your computer and use it in GitHub Desktop.
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.
/**
* @param {number[]} nums
* @return {number}
*/
var findLHS = function(nums) {
const freqMap = new Map(); // To store frequency of each number
let maxLength = 0;
// Step 1: Count the frequency of each number
for (const num of nums) {
freqMap.set(num, (freqMap.get(num) || 0) + 1);
}
// Step 2: Check if a consecutive number exists for each key
for (const [key, count] of freqMap.entries()) {
if (freqMap.has(key + 1)) {
const nextCount = freqMap.get(key + 1);
// Calculate the length of the potential harmonious subsequence
maxLength = Math.max(maxLength, count + nextCount);
}
}
return maxLength;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment