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:
The length ofnums
is at most
20000
.
Each element
nums[i]
is an integer in the range
[1, 10000]
.
感觉是比较奇怪的一道题,最开始没看到note的提示,是先对数组进行sort然后二维dp做的,不过TLE了,参考了下后面的solution,整理思路如下。
本题的关键在于note中提示的所有数字介于1到10000之间,既然给定了数字的范围,那我们很快就能联想到利用bucket sort的思路,将数组中所有的数放入到10000个bucket中,便实现了对原数组的排序。然后,对每个bucket中存的数,我们都可以采取两种策略,既取或者不取,因此我们可以对bucket从小到大遍历,对期中每个数采取这两种策略,并记录最大的取值,再遍历至下一个值。思路类似爬梯子,小偷还有买卖股票等一系列的题。
public int deleteAndEarn(int[] nums) {
int[]buckets = new int[10001];
for (Integer i:nums) {
buckets[i]++;
}
int prevNum = -1;
int includePrev = 0;
int excludePrev = 0;
for(int i = 0; i < buckets.length; i++){
if(buckets[i] != 0){
int max = Math.max(includePrev,excludePrev);
if(i != prevNum+1){
includePrev = i * buckets[i] + max;
excludePrev = max;
} else {
includePrev = i * buckets[i] + excludePrev;
excludePrev = max;
}
prevNum = i;
}
}
return Math.max(includePrev,excludePrev);
}