SDE & MLE Prep

740. Delete and Earn

Problem

Repeatedly pick a value x from nums: earn x points, then remove that element along with every element equal to x − 1 or x + 1. Return the maximum total points.

Example: [3,4,2] → 6; [2,2,3,3,3,4] → 9 (take the three 3s)

Constraints: n ≤ 2·10⁴; values ≤ 10⁴.

Taking value v earns v · count[v] and forbids v−1 and v+1 → exactly House Robber over the value axis.

Complexity: O(n + max).

class Solution:
    def deleteAndEarn(self, nums: List[int]) -> int:
        gain = [0] * (max(nums) + 1)
        for x in nums:
            gain[x] += x
        prev = cur = 0
        for g in gain:
            prev, cur = cur, max(cur, prev + g)
        return cur