forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0740-delete-and-earn.java
More file actions
25 lines (24 loc) · 879 Bytes
/
0740-delete-and-earn.java
File metadata and controls
25 lines (24 loc) · 879 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
class Solution {
public int deleteAndEarn(int[] nums) {
Map<Integer, Integer> counter = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
counter.put(nums[i], counter.getOrDefault(nums[i], 0) + 1);
}
List<Integer> numsList = new ArrayList<>(counter.keySet());
Collections.sort(numsList);
int earnOne = 0;
int earnTwo = 0;
for (int i = 0; i < numsList.size(); i++) {
int curEarn = numsList.get(i) * counter.get(numsList.get(i));
if (i > 0 && numsList.get(i) == numsList.get(i - 1) + 1) {
int temp = earnTwo;
earnTwo = Math.max(earnOne + curEarn, earnTwo);
earnOne = temp;
} else {
earnOne = earnTwo;
earnTwo += curEarn;
}
}
return earnTwo;
}
}