Skip to content

Commit a4577fc

Browse files
committed
Add solution
1 parent bce744b commit a4577fc

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// 594. Longest Harmonious Subsequence
2+
// We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1.
3+
// Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences.
4+
5+
6+
// Solution: Sorting & Sliding Window
7+
8+
// Sort nums, then maintain a sliding window where difference between first and last item is no greater than 1.
9+
// Record the maximum length of the sliding window.
10+
11+
// Time Complexity: O(n log(n)) 45ms
12+
// Space Complexity: O(log(n)) 60MB
13+
function findLHS(nums) {
14+
nums.sort((a, b) => a - b);
15+
const n = nums.length;
16+
let lhs = 0;
17+
for (let j = 0, i = 0; j < n; j++) {
18+
while (nums[j] - nums[i] > 1) i++;
19+
if (nums[j] - nums[i] > 0) {
20+
lhs = Math.max(lhs, j - i + 1);
21+
}
22+
}
23+
return lhs;
24+
};
25+
26+
// Three test cases
27+
console.log(findLHS([1,3,2,2,5,2,3,7])) // 5
28+
console.log(findLHS([1,2,3,4])) // 2
29+
console.log(findLHS([1,1,1,1])) // 0

0 commit comments

Comments
 (0)