Given an array
nums
of integers, you can perform operations on the array.
In each operation, you pick any
nums[i]
and delete it to earn nums[i]
points. After, you must delete every element equal to nums[i] - 1
or nums[i] + 1
.
You start with 0 points. Return the maximum number of points you can earn by applying such operations.
Example 1:
Input: nums = [3, 4, 2] Output: 6 Explanation: Delete 4 to earn 4 points, consequently 3 is also deleted. Then, delete 2 to earn 2 points. 6 total points are earned.
Example 2:
Input: nums = [2, 2, 3, 3, 3, 4] Output: 9 Explanation: Delete 3 to earn 3 points, deleting both 2's and the 4. Then, delete 3 again to earn 3 points, and 3 again to earn 3 points. 9 total points are earned.
Note:
nums
is at most 20000
.nums[i]
is an integer in the range [1, 10000]
.Analysis:
There are several tricks in the problem.
-- Since each element nums[i] is within the range of [1, 10000], we can use the bucket sort to sort the nums.
-- For deleting each nums[i], we can delete all same numbers together. So when we do the bucket sort, we can sum up all the repeated numbers in the same bucket.
-- Then the problem is a classic backpack problem.
Define take[10001] and skip[10001], where take[i] means for number i, we delete the number i, the max number of points. skip[i] means we don't delete it.
Then the transit function should be:
take[i] = skip[i - 1] + values[i]
skip[i] = Math.max(take[i - 1], skip[i - 1]);
Code (Java):
class Solution { public int deleteAndEarn(int[] nums) { int[] dp = new int[100001]; // step 1: bucket sort // for (int num : nums) { dp[num] += num; } int prevTake = 0; int prevSkip = 0; for (int i = 1; i <= 10000; i++) { int currTake = prevSkip + dp[i]; int currSkip = Math.max(prevSkip, prevTake); prevTake = currTake; prevSkip = currSkip; } return Math.max(prevTake, prevSkip); } }
No comments:
Post a Comment