Skip to problem
←

Delete and Earn

Medium 0 attempts

Given an integer array nums, repeatedly choose one element with value x and remove it to earn x points. You must also remove every remaining element equal to x - 1 or x + 1, earning no points for those removals.

Other occurrences of x remain available to choose in later moves. Return the maximum total points you can earn.

Function contract

Implement deleteAndEarn(nums), where nums contains positive integers. Choosing one occurrence of x earns x points and deletes all remaining values x - 1 and x + 1.

Output: The maximum total points obtainable by repeatedly choosing remaining elements. Other occurrences of x remain available after choosing x.

Example 1

Input
nums = [3,4,2]
Output
6

Explanation: Choose 4 to earn 4 and delete 3. Then choose 2 to earn 2 more, for a total of 6.

Example 2

Input
nums = [2,2,3,3,3,4]
Output
9

Explanation: Choose all three occurrences of 3, earning 9. Choosing the first 3 removes every 2 and 4.

Constraints
  • 1 <= nums.length <= 2 * 10^4
  • 1 <= nums[i] <= 10^4

House Robber on Frequency Array

Once you choose a value, choosing all its remaining occurrences can only help: the neighboring values have already been removed. Group their points into sums[value]. Then select nonadjacent values using the House Robber recurrence.

javascript
function deleteAndEarn(nums) {
  let max = 0;
  for (const value of nums) max = Math.max(max, value);
  const sums = Array(max + 1).fill(0);
  for (const n of nums) sums[n] += n;
  let prev = 0, curr = 0;
  for (let i = 0; i <= max; i++) [prev, curr] = [curr, Math.max(curr, prev + sums[i])];
  return curr;
}

Time: O(n + max) | Space: O(max)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript