Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit53b4295

Browse files
refactor 740
1 parent2d9d371 commit53b4295

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

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
packagecom.fishercoder.solutions;
22

3+
importjava.util.TreeMap;
4+
35
publicclass_740 {
46
publicstaticclassSolution1 {
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
publicintdeleteAndEarn(int[]nums) {
1620
intn =10001;
@@ -30,4 +34,29 @@ public int deleteAndEarn(int[] nums) {
3034
returnMath.max(take,skip);
3135
}
3236
}
37+
38+
publicstaticclassSolution2 {
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+
publicintdeleteAndEarn(int[]nums) {
43+
TreeMap<Integer,Integer>treeMap =newTreeMap<>();
44+
for (intnum :nums) {
45+
treeMap.put(num,treeMap.getOrDefault(num,0) +num);
46+
}
47+
intprev =0;
48+
intcurr =0;
49+
for (intkey :treeMap.keySet()) {
50+
if (!treeMap.containsKey(key -1)) {
51+
prev =curr;
52+
curr +=treeMap.get(key);
53+
}else {
54+
inttmp =Math.max(prev +treeMap.get(key),curr);
55+
prev =curr;
56+
curr =tmp;
57+
}
58+
}
59+
returncurr;
60+
}
61+
}
3362
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp