Delete and Earn
Difficulty: Medium · Pattern: 1-D Dynamic Programming · LeetCode #740
Pick any nums[i] to earn nums[i] points. Doing so deletes every element equal to nums[i] − 1 and nums[i] + 1. Repeat as long as you like. Return the maximum points.
Examples
text
[3,4,2] → 6 (take 4 → deletes 3; take 2)
[2,2,3,3,3,4] → 9 (take all three 3s)Hints
- If you take one copy of value v, you should take all of them.
- Let
points[v] = v × count(v). Taking v forbids v−1 and v+1. Does that look familiar?
Approach
Reduce to House Robber:
points[v] = v × count[v]for v from 0 to max(nums).- Rob the "houses"
points[0..max], where adjacent values can't both be taken:cur = max(cur, prev + points[v]).
O(n + maxVal). If the values are huge and sparse, sort the distinct values instead and treat non-adjacent values (gap > 1) as independent.
Recognizing a known DP under a disguise is the skill this problem tests.
Complexity
Time: O(n + max). Space: O(max).
Python solution
def deleteAndEarn(nums):
m = max(nums)
points = [0] * (m + 1)
for x in nums:
points[x] += x
prev = cur = 0
for p in points:
prev, cur = cur, max(cur, prev + p)
return curJavaScript solution
function deleteAndEarn(nums) {
const m = Math.max(...nums), points = new Array(m + 1).fill(0);
for (const x of nums) points[x] += x;
let prev = 0, cur = 0;
for (const p of points) [prev, cur] = [cur, Math.max(cur, prev + p)];
return cur;
}