Skip to content

Delete and Earn

MediumDynamic Programming
Decode it first. Clues, constraints, pattern and plan before any code.

You are given an array nums. In one move you pick any nums[i], earn nums[i] points, and remove it. Every element equal to nums[i] - 1 or nums[i] + 1 is then deleted too, for no points. Return the maximum points you can earn.

nums = [3, 4, 2]           →  6   (take 4, which deletes the 3; then take 2)
nums = [2, 2, 3, 3, 3, 4]  →  9   (take all three 3s)
nums = [1]                 →  1

Constraints

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