LeetCode: Longest Harmonious Subsequence Solution
Approach
As the sequence only the max and the min whose diff is 1
Use the hash table for element and its occurence
Implementation
1/**2 * @param {number[]} nums3 * @return {number}4 */5var findLHS = function (nums) {6 const elOccMap = nums.reduce(7 (acc, el) => acc.set(el, (acc.get(el) || 0) + 1),8 new Map()9 )10 let max = 011 for (const [el, occ] of elOccMap) {12 if (elOccMap.get(el + 1)) {13 max = Math.max(max, occ + elOccMap.get(el + 1))14 }15 }16 return max17}
Comments
Loading comments...
Tags
leetcode
hash table
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.