类似于打家劫舍 dp问题
学习一下 冲冲冲
谢谢三叶姐
class Solution {
int[] s = new int[10010];
public int deleteAndEarn(int[] nums) {
int max = 0;
for(int num : nums){
s[num] ++;
max = Math.max(max, num);
}
int f[][] = new int[max + 1][2];
for(int i = 1; i <= max; i++){
f[i][1] = f[i - 1][0] + i * s[i];
f[i][0] = Math.max(f[i - 1][1], f[i - 1][0]);
}
return Math.max(f[max][0], f[max][1]);
}
}
class Solution {
public int deleteAndEarn(int[] nums) {
int maxnum = nums[0];
if (nums == null || nums.length == 0) {
return 0;
}
if(nums.length == 1){
return nums[0];
}
for(int i = 1; i < nums.length; i++){
maxnum = Math.max(maxnum, nums[i]);
}
int[] all = new int[maxnum + 1];
for(int item : nums){
all[item]++;
}
int[] dp = new int[maxnum + 1];
dp[1] = all[1] * 1;
dp[2] = Math.max(dp[2], all[2] * 2);
for(int i = 2; i <= maxnum; ++i){
dp[i] = Math.max(dp[i - 1], dp[i - 2] + all[i] * i);
}
return dp[maxnum];
}
}
|