-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.js
47 lines (43 loc) · 1.42 KB
/
solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* @param {number[]} nums
* @return {number}
*/
var findLHS = function(nums) {
let maxLength = 0,
harmoniousMap = new Map()
nums.forEach(num => {
let prevKey = `${num - 1}X${num}`,
nextKey = `${num}X${num + 1}`
if (harmoniousMap.get(prevKey) === undefined) {
harmoniousMap.set(prevKey, {
length: 1,
base: num,
isHarmonious: false
})
} else {
harmoniousMap.get(prevKey).length++
if (harmoniousMap.get(prevKey).base !== num) {
harmoniousMap.get(prevKey).isHarmonious = true
}
if (harmoniousMap.get(prevKey).isHarmonious) {
maxLength = Math.max(maxLength, harmoniousMap.get(prevKey).length)
}
}
if (harmoniousMap.get(nextKey) === undefined) {
harmoniousMap.set(nextKey, {
length: 1,
base: num,
isHarmonious: false
})
} else {
harmoniousMap.get(nextKey).length++
if (harmoniousMap.get(nextKey).base !== num) {
harmoniousMap.get(nextKey).isHarmonious = true
}
if (harmoniousMap.get(nextKey).isHarmonious) {
maxLength = Math.max(maxLength, harmoniousMap.get(nextKey).length)
}
}
})
return maxLength
};