Delete and Earn

Medium

Topics
ArrayHash TableDynamic ProgrammingCounting

You are given an integer array nums. In one operation you pick any element, earn nums[i] points, and then every element equal to nums[i] - 1 and every element equal to nums[i] + 1 is deleted along with it.

Return the maximum points you can earn by applying the operation any number of times.

Example 1

2 x1 = 23 x1 = 34 x1 = 4
takendeleted by a neighbour
Taking a value earns every copy of it and deletes every copy of the value one above and one below — so the chips are values, not elements, and two chips conflict only when their values are adjacent. The shaded choice earns 6, and nothing earns more.
One chip per distinct value: the value, how many copies it has, and what they are worth together.
Input:  nums = [3,4,2]
Output: 6
Explanation: Take 4, which deletes the 3. Then take 2 for a total of 6. Taking 3 first would delete both others for only 3.

Example 2

2 x2 = 43 x3 = 94 x1 = 4
takendeleted by a neighbour
Input:  nums = [2,2,3,3,3,4]
Output: 9
Explanation: Taking a 3 deletes every 2 and every 4, but there are three 3s and they are all still available: 3 + 3 + 3 = 9.

Example 3

1 x1 = 1
taken
Input:  nums = [1]
Output: 1
Explanation: One element, nothing adjacent to delete.

Constraints

  • 1 <= nums.length <= 2 * 10^4
  • 1 <= nums[i] <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

The operation is described per element, and example 2 shows it really acts per value: taking one 3 removes all the 2s and 4s but leaves the other 3s untouched, so once you take a value you may as well take every copy of it. Nothing is lost by doing so and the deletions have already happened.

That collapses the input to a score per value: value × how many times it appears. And the constraint becomes simple — choosing a value forbids the values one above and one below it.

What is left is a line of scores indexed by value, where no two neighbouring indices may both be chosen. That is the same shape as the problem of robbing houses along a street, and the reason the array of counts is indexed by value rather than by position is that adjacency here means numeric adjacency.

The gaps matter: values with no copies score zero, and a gap of two or more in the input means the two sides are independent. Indexing by value handles that automatically, where iterating over the sorted distinct values needs an explicit check.

Approach

  1. Count the occurrences of each value and compute points[v] = v × count(v).
  2. Sweep v from the smallest value to the largest, carrying two running totals: the best achievable using values up to v, and the best using values up to v - 1.
  3. At each v, either skip it — keeping the previous best — or take it, which adds points[v] to the best from v - 2.
  4. The larger of the two becomes the new best, and the final best is the answer.

Walkthrough

nums = [2,2,3,3,3,4]

points per value
   2 -> 2 x 2 = 4
   3 -> 3 x 3 = 9
   4 -> 4 x 1 = 4

sweep (best = best using values up to v)
 v   points   skip   take            best
 1     0        0     0 + 0 = 0        0
 2     4        0     0 + 4 = 4        4
 3     9        4     0 + 9 = 9        9
 4     4        9     4 + 4 = 8        9

answer 9

At v = 4 taking it is worth 8, which is less than the 9 the
3s already earned -- so the three 3s win over the 2s and the
4 together.

Complexity

  • Time — O(n + k log k): one pass to count, then a sweep over the distinct values in sorted order.
  • Space — O(k): one entry per distinct value.

Common Pitfalls

  • Treating the operation as removing one element rather than one value. Taking a 3 does not consume the other 3s, and example 2 is 9 rather than 3 because of it.
  • Iterating over the sorted distinct values without checking for a gap. After a gap the previous value is not a conflict, so the "take" branch must be allowed to build on the immediately preceding best.
  • Assigning the two running totals one at a time without a temporary. The second assignment then reads the value the first just overwrote.
  • Sorting the input and treating positional neighbours as conflicts. Adjacency is numeric: 2 and 4 never conflict however they are arranged.

Full Solution — all languages

class Solution:
    def deleteAndEarn(self, nums):
        points = {}
        for v in nums:
            points[v] = points.get(v, 0) + v
        best_here = 0
        best_before = 0
        previous = None
        for v in sorted(points):
            if previous is not None and v == previous + 1:
                take = best_before + points[v]
                best_before, best_here = best_here, max(best_here, take)
            else:
                best_before, best_here = best_here, best_here + points[v]
            previous = v
        return best_here
SensAI
Beta
Tap the mic to stop voice mode