Skip to content

Commit 331870a

Browse files
committed
0740 Delete and Earn新增Java解
1 parent 7838230 commit 331870a

File tree

1 file changed

+37
-2
lines changed
  • solution/0700-0799/0740.Delete and Earn

1 file changed

+37
-2
lines changed

solution/0700-0799/0740.Delete and Earn/README.md

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,24 @@
4343
## 解法
4444
<!-- 这里可写通用的实现逻辑 -->
4545

46-
4746
<!-- tabs:start -->
47+
核心思路: **一个数字要么不选,要么全选**
48+
49+
首先计算出每个数字的总和sums,并维护两个dp数组:select和nonSelect
50+
51+
- sums[i]代表值为i的元素总和
52+
- select[i]代表如果选数字i,从0处理到i的最大和
53+
- nonSelect[i]代表如果不选数字i,从0处理到i的最大和
54+
55+
那么我们有以下逻辑:
56+
57+
- 如果选i,那么i-1肯定不能选;
58+
- 如果不选i,那么i-1选不选都可以,因此我们选择其中较大的选法
59+
60+
``` java
61+
select[i] = nonSelect[i-1] + sums[i];
62+
nonSelect[i] = Math.max(select[i-1], nonSelect[i-1]);
63+
```
4864

4965
### **Python3**
5066
<!-- 这里可写当前语言的特殊实现逻辑 -->
@@ -57,10 +73,29 @@
5773
<!-- 这里可写当前语言的特殊实现逻辑 -->
5874

5975
```java
60-
76+
class Solution {
77+
public int deleteAndEarn(int[] nums) {
78+
if (nums.length == 0) {
79+
return 0;
80+
}
81+
int[] sums = new int[10010];
82+
for (int x : nums) {
83+
sums[x] += x;
84+
}
85+
int[] select = new int[10010];
86+
int[] nonSelect = new int[10010];
87+
for (int i = 1; i <= 10000; i++) {
88+
select[i] = nonSelect[i - 1] + sums[i];
89+
nonSelect[i] = Math.max(select[i - 1], nonSelect[i - 1]);
90+
}
91+
92+
return Math.max(select[10000], nonSelect[10000]);
93+
}
94+
}
6195
```
6296

6397
### **...**
98+
6499
```
65100
66101
```

0 commit comments

Comments
 (0)