Skip to content

Commit acea060

Browse files
committedJan 18, 2025
Add solution #594
1 parent 7415738 commit acea060

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed
 

‎README.md

+1
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,7 @@
234234
566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy|
235235
567|[Permutation in String](./0567-permutation-in-string.js)|Medium|
236236
575|[Distribute Candies](./0575-distribute-candies.js)|Easy|
237+
594|[Longest Harmonious Subsequence](./0594-longest-harmonious-subsequence.js)|Easy|
237238
599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy|
238239
605|[Can Place Flowers](./0605-can-place-flowers.js)|Easy|
239240
606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* 594. Longest Harmonious Subsequence
3+
* https://leetcode.com/problems/longest-harmonious-subsequence/
4+
* Difficulty: Easy
5+
*
6+
* We define a harmonious array as an array where the difference between its maximum
7+
* value and its minimum value is exactly 1.
8+
*
9+
* Given an integer array nums, return the length of its longest harmonious subsequence
10+
* among all its possible subsequences.
11+
*/
12+
13+
/**
14+
* @param {number[]} nums
15+
* @return {number}
16+
*/
17+
var findLHS = function(nums) {
18+
const map = new Map();
19+
nums.forEach(n => map.set(n, (map.get(n) ?? 0) + 1));
20+
21+
return Array.from(map).reduce((result, [n, count]) => {
22+
return map.has(n + 1) ? Math.max(result, count + map.get(n + 1)) : result;
23+
}, 0);
24+
};

0 commit comments

Comments
 (0)
Please sign in to comment.