-
-
Notifications
You must be signed in to change notification settings - Fork 9.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
luzhipeng
committed
Jun 20, 2019
1 parent
53313e5
commit e911f7c
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
/* | ||
* @lc app=leetcode id=594 lang=javascript | ||
* | ||
* [594] Longest Harmonious Subsequence | ||
*/ | ||
/** | ||
* @param {number[]} nums | ||
* @return {number} | ||
*/ | ||
var findLHS = function(nums) { | ||
// Input: [1,3,2,2,5,2,3,7] | ||
// Output: 5 | ||
// Explanation: The longest harmonious subsequence is [3,2,2,2,3]. | ||
if (nums.length === 0) return 0; | ||
const counts = {}; | ||
let res = 0; | ||
|
||
for (let i = 0; i < nums.length; i++) { | ||
if (!counts[nums[i]]) { | ||
counts[nums[i]] = 1; | ||
} else { | ||
counts[nums[i]] += 1; | ||
} | ||
} | ||
|
||
for (let i = 0; i < nums.length; i++) { | ||
if (counts[nums[i] + 1]) { | ||
res = Math.max(res, counts[nums[i]] + counts[nums[i] + 1]); | ||
} | ||
} | ||
|
||
return res; | ||
}; |