Delete and Earn
Medium
Topics
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
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
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
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
- Count the occurrences of each value and compute
points[v] = v × count(v). - Sweep
vfrom the smallest value to the largest, carrying two running totals: the best achievable using values up tov, and the best using values up tov - 1. - At each
v, either skip it — keeping the previous best — or take it, which addspoints[v]to the best fromv - 2. - 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_hereimport java.util.*;
class Solution {
public int deleteAndEarn(int[] nums) {
TreeMap<Integer, Long> points = new TreeMap<>();
for (int v : nums) points.merge(v, (long) v, Long::sum);
long bestHere = 0, bestBefore = 0;
Integer previous = null;
for (Map.Entry<Integer, Long> e : points.entrySet()) {
long nextHere;
if (previous != null && e.getKey() == previous + 1) {
nextHere = Math.max(bestHere, bestBefore + e.getValue());
} else {
nextHere = bestHere + e.getValue();
}
bestBefore = bestHere;
bestHere = nextHere;
previous = e.getKey();
}
return (int) bestHere;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int deleteAndEarn(vector<int>& nums) {
map<int, long long> points;
for (int v : nums) points[v] += v;
long long bestHere = 0, bestBefore = 0;
int previous = INT_MIN;
for (auto& kv : points) {
long long nextHere;
if (previous != INT_MIN && kv.first == previous + 1) {
nextHere = max(bestHere, bestBefore + kv.second);
} else {
nextHere = bestHere + kv.second;
}
bestBefore = bestHere;
bestHere = nextHere;
previous = kv.first;
}
return (int)bestHere;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var deleteAndEarn = function(nums) {
const points = new Map();
for (const v of nums) points.set(v, (points.get(v) || 0) + v);
const values = [...points.keys()].sort((x, y) => x - y);
let bestHere = 0, bestBefore = 0, previous = null;
for (const v of values) {
let nextHere;
if (previous !== null && v === previous + 1) {
nextHere = Math.max(bestHere, bestBefore + points.get(v));
} else {
nextHere = bestHere + points.get(v);
}
bestBefore = bestHere;
bestHere = nextHere;
previous = v;
}
return bestHere;
};