Delete and Earn
Problem statement
You are given an integer array nums. Repeatedly choose one remaining occurrence of a value x, add x to your score, and remove that occurrence. Also remove every remaining occurrence of x - 1 and x + 1 without scoring them.
Other occurrences of x remain available. Continue until the array is empty. Return the maximum total score obtainable over all choices.
For this exercise, assume the score for an empty input is zero.
Function
deleteAndEarn(nums: int[]) → intExamples
Example 1
nums = [8,3,4,2,2,7]return = 16Choose both occurrences of 2, then 4 and 8, earning 2 + 2 + 4 + 8 = 16. Choosing 2 removes 3; choosing 8 removes 7. These choices attain the maximum.
Example 2
nums = [2,3]return = 3Choosing 2 first earns only 2; choosing 3 first earns 3. The score depends on the choice, and the maximum is 3.
Constraints
- For this exercise, assume 0 <= nums.length <= 20000.
- For this exercise, assume 1 <= nums[i] <= 10000.