File tree Expand file tree Collapse file tree 1 file changed +37
-2
lines changed
solution/0700-0799/0740.Delete and Earn Expand file tree Collapse file tree 1 file changed +37
-2
lines changed Original file line number Diff line number Diff line change 43
43
## 解法
44
44
<!-- 这里可写通用的实现逻辑 -->
45
45
46
-
47
46
<!-- 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
+ ```
48
64
49
65
### ** Python3**
50
66
<!-- 这里可写当前语言的特殊实现逻辑 -->
57
73
<!-- 这里可写当前语言的特殊实现逻辑 -->
58
74
59
75
``` 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
+ }
61
95
```
62
96
63
97
### ** ...**
98
+
64
99
```
65
100
66
101
```
You can’t perform that action at this time.
0 commit comments