Delete and Earn

Earn the most points from an array when taking a number also deletes every number one above or one below it.

Given an array of positive integers nums, play a game of moves. In one move, pick any element nums[i], earn nums[i] points, and delete it. Every element equal to nums[i] - 1 or nums[i] + 1 is deleted too, without earning anything. Return the largest total of points you can earn, making as many moves as you like.

Example 1
Input: nums = [3, 4, 2]
Output: 6
Explanation: take 4 for 4 points, which also deletes 3. Then take 2 for 2 points.
Example 2
Input: nums = [2, 2, 3, 3, 3, 4]
Output: 9
Explanation: take a 3, which deletes both 2s and the 4. Then take the other two 3s, for 3 + 3 + 3 = 9.
Solution

The Idea

Picture a bag of number tokens. Each token you take is worth its number, but taking a 3 makes you throw away every token marked 2 or 4. Example 2 is a bag of six tokens: two 2s, three 3s and one 4.

Follow one game. Take a 3 and earn 3 points, and the two 2s and the 4 go in the bin. Two 3s are left, and taking them costs nothing more, because the 2s and the 4 are already gone. This game ends with 9 points.

Another game starts with the 4. It earns 4 and throws away all three 3s. The two 2s are still in the bag, worth 4 more, so this game ends with 8. Which first move is right, and how can we tell without playing every possible game?

Look at the first game again. Once one 3 is taken, the other 3s are free. So for each value, you take all its copies or none, and taking a value v earns v times its number of copies. In Example 2, the 2s are worth 4 together, the 3s are worth 9, and the 4 is worth 4.

Now line the values up in order: 0, 1, 2, 3, 4. Taking a value rules out the values right next to it in the line, and nothing else. The question becomes: which values do we take, with no two side by side, to make the biggest total? It is the same question as House Robber, with the values as the houses and each value's points as a house's money.

Walk along the line and keep one number for each value: the best total that uses only the values up to it. Look at the picture below.

For nums = [2, 2, 3, 3, 3, 4], the row labelled points for every copy reads 0, 0, 4, 9, 4 for the values 0 to 4. The row labelled best total up to here reads 0, 0, 4, 9, 9. At value 4, taking it gives 4 + 4 = 8 and skipping it keeps 9.

The row labelled points for every copy holds the totals worked out for Example 2, with 0 for the values 0 and 1, which never appear. The row labelled best total up to here fills from left to right. Look at value 4, whose box in the bottom row is outlined in orange. Taking 4 rules out 3, so its 4 points add to the best total up to 2: 4 + 4 = 8. Skipping 4 keeps the best total up to 3, which is 9. The larger, 9, is the answer to Example 2.

Each entry in that bottom row comes from the two entries just before it, so the best total for a short stretch of values is worked out once and reused by the longer stretches. Building the answer for the values 0 to 4 out of the answers for 0 to 2 and 0 to 3 this way is called dynamic programming.

Solution Approach

Turning the line of values into code means seeing why trying every game is slow, then settling how to total the points per value and how to fill the best totals, which can optionally shrink to two variables.

Trying every choice of values

Why not simply try every game? Since each value is taken whole or not at all, a game comes down to a choice of which different values to take. With k different values there are 2k choices: 8 for Example 2, but over a million for 20 values. The line of best totals looks at each value once instead.

Could we just grab the most valuable value first? In [1, 1, 1, 2, 2, 3], the 1s are worth 3, the 2s are worth 4, and the 3 is worth 3. Grabbing the 2s first earns 4 and deletes every other token, while taking the 1s and the 3 earns 6.

Totals per value

Where do the totals for each value go? Into an array points indexed by the value itself, so points[v] is what taking every copy of v earns. Its size is the largest value plus one, and one pass over nums adds each element v to points[v].

In this array, neighbouring positions are values that differ by 1, which are exactly the values that rule each other out. Values that never appear stay at 0 and leave a gap. In [1, 3, 5] no two values are next to each other, so all three can be taken, for 9 points.

Filling the best totals

What does one entry of the bottom row mean in code? In an array best, best[v] is the most points from the values 0 to v. For each v there are two choices. Skip v, and the total stays best[v - 1]. Take v, and v - 1 is ruled out, so the total is best[v - 2] + points[v].

best[v] is the larger of the two. The start needs care: best[0] is just points[0], and at v = 1 the take choice is points[1] alone, because there is no value -1. The answer is the last entry, the best total over every value.

Optional: two variables instead of an array

Does the whole best array need to be kept? Each step reads only the two entries just before it, so two variables, one for the best total up to the previous value and one for the value before that, are enough. The points array still has one entry per value, so the memory still grows with the largest value. The code below keeps best as an array so main can print the bottom row of the picture.

Java Solution

The method deleteAndEarn works in these steps:

  1. First, a helper method, pointsPerValue, finds the largest value, max, with one loop over nums, and creates the array points with max + 1 entries. A second loop adds each element v to points[v].
  2. Next, a second helper, bestTotals, creates the array best, as long as points, and sets best[0] to points[0].
  3. A loop then moves v from 1 to the last value. For each v, skip is best[v - 1], and take is points[v] plus best[v - 2], or plus 0 when v is 1. best[v] gets the larger of the two.
  4. Finally, deleteAndEarn returns the last entry of best.

The main method prints points and best for Example 2, then runs both examples, the array [1, 1, 1, 2, 2, 3], the gapped array [1, 3, 5] and the single element [7].

Java
import java.util.Arrays;

public class DeleteAndEarn {

    public static int deleteAndEarn(int[] nums) {
        int[] points = pointsPerValue(nums);
        int[] best = bestTotals(points);
        return best[best.length - 1];
    }

    // points[v]: what taking every copy of v earns
    static int[] pointsPerValue(int[] nums) {
        int max = 0;
        for (int v : nums) {
            max = Math.max(max, v);
        }
        int[] points = new int[max + 1];
        for (int v : nums) {
            points[v] += v;
        }
        return points;
    }

    // best[v]: the most points from the values 0 to v
    static int[] bestTotals(int[] points) {
        int[] best = new int[points.length];
        best[0] = points[0];
        for (int v = 1; v < points.length; v++) {
            int skip = best[v - 1];                            // leave v out
            int take = (v >= 2 ? best[v - 2] : 0) + points[v]; // take v, so not v - 1
            best[v] = Math.max(skip, take);
        }
        return best;
    }

    public static void main(String[] args) {
        int[] example2 = {2, 2, 3, 3, 3, 4};
        int[] points = pointsPerValue(example2);
        System.out.println("points = " + Arrays.toString(points));
        System.out.println("best   = " + Arrays.toString(bestTotals(points)));
        System.out.println(deleteAndEarn(new int[] {3, 4, 2}));
        System.out.println(deleteAndEarn(example2));
        System.out.println(deleteAndEarn(new int[] {1, 1, 1, 2, 2, 3}));
        System.out.println(deleteAndEarn(new int[] {1, 3, 5}));
        System.out.println(deleteAndEarn(new int[] {7}));
    }
}

Running it prints:

Output
points = [0, 0, 4, 9, 4]
best   = [0, 0, 4, 9, 9]
6
9
6
9
7

The points and best lines match the two lower rows of the picture, and the last entry of best, 9, comes back as Example 2's answer on the fourth line. Example 1 prints 6 just above it: its values 2 and 4 together beat 3 on its own.

The fifth line, 6, is [1, 1, 1, 2, 2, 3], where the 1s and the 3 beat the more valuable 2s. [1, 3, 5] prints 9, every value taken across the gaps, and [7] prints 7, because best carries the zeros for 0 to 6 forward and then takes 7.

Complexity

The work is two passes over nums plus one pass over the values from 0 up to the largest one, which we call M.

  • Time: O(n + M), because two loops over the n elements of nums find the largest value and fill points, and the loop that fills best visits each of the M + 1 values once.
  • Space: O(M), because points and best each hold one entry for every value from 0 to M, even for values that never appear in nums.