-
Notifications
You must be signed in to change notification settings - Fork 413
Expand file tree
/
Copy pathcode.js
More file actions
48 lines (38 loc) · 993 Bytes
/
code.js
File metadata and controls
48 lines (38 loc) · 993 Bytes
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
48
/**
* @param {number[]} nums
* @return {number}
*/
var deleteAndEarn = function(nums) {
const hash = new Map();
nums.forEach((num) => {
const numCache = hash.get(num);
if(numCache) {
hash.set(num, numCache + 1);
} else {
hash.set(num, 1);
}
});
const uniqueNums = new Set();
nums.forEach((num) => {
uniqueNums.add(num);
});
nums = [...uniqueNums];
nums.sort((a,b) => {
return a-b;
});
let earn1 = 0;
let earn2 = 0;
for(let i = 0; i < nums.length; i++) {
const currentEarn = nums[i] * hash.get(nums[i]);
if(nums[i] === nums[i-1] + 1) {
const temp = earn2;
earn2 = Math.max(earn2, currentEarn + earn1);
earn1 = temp;
} else {
const temp = earn2;
earn2 = currentEarn + earn2;
earn1 = temp;
}
}
return earn2;
};