Skip to content

Commit 415c59c

Browse files
authored
Create 740_Delete_and_Earn.md
1 parent 95678ff commit 415c59c

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

740_Delete_and_Earn.md

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
## 740. Delete and Earn
2+
3+
4+
```
5+
Given an array nums of integers, you can perform operations on the array.
6+
7+
In each operation, you pick any nums[i] and delete it to earn nums[i] points. After, you must delete every element equal to nums[i] - 1 or nums[i] + 1.
8+
9+
You start with 0 points. Return the maximum number of points you can earn by applying such operations.
10+
11+
12+
13+
Example 1:
14+
15+
Input: nums = [3,4,2]
16+
Output: 6
17+
Explanation: Delete 4 to earn 4 points, consequently 3 is also deleted.
18+
Then, delete 2 to earn 2 points.
19+
6 total points are earned.
20+
Example 2:
21+
22+
Input: nums = [2,2,3,3,3,4]
23+
Output: 9
24+
Explanation: Delete 3 to earn 3 points, deleting both 2's and the 4.
25+
Then, delete 3 again to earn 3 points, and 3 again to earn 3 points.
26+
9 total points are earned.
27+
28+
29+
Constraints:
30+
31+
1 <= nums.length <= 2 * 104
32+
1 <= nums[i] <= 104
33+
```
34+
35+
36+
```python
37+
class Solution:
38+
def deleteAndEarn(self, nums: List[int]) -> int:
39+
40+
41+
# [2,5,5,6,6,4,4,10,10,10]
42+
# 1 2. 3. 4. 5. 6. 7. 8. 9 10
43+
# [0, 2, 0, 8, 10, 12, 0, 0, 0, 30]
44+
# convert array for house rubber
45+
46+
# convert arr for house robber
47+
max_val = max(nums)
48+
arr = [0] * max_val
49+
50+
for num in nums:
51+
arr[num-1] += num
52+
53+
size = len(arr)
54+
if size == 1:
55+
return arr[0]
56+
dp = [0] * (size)
57+
dp[0] = arr[0]
58+
dp[1] = max(arr[0], arr[1])
59+
60+
for i in range(2, size):
61+
dp[i] = max(dp[i-1], dp[i-2] + arr[i])
62+
63+
return dp[-1]
64+
```
65+
66+
67+
```
68+
Runtime: 56 ms, faster than 69.52% of Python3 online submissions for Delete and Earn.
69+
Memory Usage: 14.7 MB, less than 28.38% of Python3 online submissions for Delete and Earn.
70+
```

0 commit comments

Comments
 (0)