Skip to content

Commit 53b4295

Browse files
refactor 740
1 parent 2d9d371 commit 53b4295

File tree

1 file changed

+30
-1
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+30
-1
lines changed

src/main/java/com/fishercoder/solutions/_740.java

+30-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package com.fishercoder.solutions;
22

3+
import java.util.TreeMap;
4+
35
public class _740 {
46
public static class Solution1 {
57
/**
@@ -10,7 +12,9 @@ public static class Solution1 {
1012
* <p>
1113
* credit: https://leetcode.com/problems/delete-and-earn/discuss/109895/JavaC++-Clean-Code-with-Explanation
1214
* <p>
13-
* In essence, this is the same as House Robber: https://leetcode.com/problems/house-robber/
15+
* Notes:
16+
* 1. In essence, this is the same as House Robber: https://leetcode.com/problems/house-robber/
17+
* 2. We are adding the number itself into values, instead of its frequency because we will directly use this value to compute the result
1418
*/
1519
public int deleteAndEarn(int[] nums) {
1620
int n = 10001;
@@ -30,4 +34,29 @@ public int deleteAndEarn(int[] nums) {
3034
return Math.max(take, skip);
3135
}
3236
}
37+
38+
public static class Solution2 {
39+
/**
40+
* A simplified version using treemap instead of an array, credit: https://leetcode.com/problems/delete-and-earn/discuss/109895/JavaC++-Clean-Code-with-Explanation/111626
41+
*/
42+
public int deleteAndEarn(int[] nums) {
43+
TreeMap<Integer, Integer> treeMap = new TreeMap<>();
44+
for (int num : nums) {
45+
treeMap.put(num, treeMap.getOrDefault(num, 0) + num);
46+
}
47+
int prev = 0;
48+
int curr = 0;
49+
for (int key : treeMap.keySet()) {
50+
if (!treeMap.containsKey(key - 1)) {
51+
prev = curr;
52+
curr += treeMap.get(key);
53+
} else {
54+
int tmp = Math.max(prev + treeMap.get(key), curr);
55+
prev = curr;
56+
curr = tmp;
57+
}
58+
}
59+
return curr;
60+
}
61+
}
3362
}

0 commit comments

Comments
 (0)