Skip to content

Commit

Permalink
feat: 每日一题参考答案2019-06-20
Browse files Browse the repository at this point in the history
  • Loading branch information
luzhipeng committed Jun 20, 2019
1 parent 53313e5 commit e911f7c
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions daily/answers/594.longest-harmonious-subsequence.js
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;
};

0 comments on commit e911f7c

Please sign in to comment.