public class Test2 {
public static void main(String[] args) {
int[] nums={3,4,2};
Test2 test2=new Test2();
test2.deleteAndEarn(nums);
}
public int deleteAndEarn(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
} else if (nums.length == 1) {
return nums[0];
}
int len = nums.length;
int max = nums[0];
for (int i = 0; i < len; ++i) {
max = Math.max(max, nums[i]);
}
// 构造一个新的数组all 记录个数
int[] all = new int[max + 1];
for (int item : nums) {
all[item] ++;
}
int[] dp = new int[max + 1];
dp[1] = all[1] * 1;
dp[2] = Math.max(dp[1], all[2] * 2);
// 动态规划求解
for (int i = 2; i <= max; ++i) {
dp[i] = Math.max(dp[i - 1], dp[i - 2] + i * all[i]);
}
return dp[max];
}
}
740. Delete and Earn
最新推荐文章于 2024-11-03 21:27:26 发布