编程语言
首页 > 编程语言> > LeetCode740. 删除并获得点数(java/c++动态规划)

LeetCode740. 删除并获得点数(java/c++动态规划)

作者:互联网

740. 删除并获得点数(动态规划)

链接:https://leetcode-cn.com/problems/delete-and-earn/solution/javadong-tai-gui-hua-100da-jia-jie-she-b-n5o7/

解题思路
没做过打家劫舍的可以先做做198.打家劫舍

创建一个新数组count,对nums[i]计数,将这个题转换为打家劫舍的思路
推导公式为 dp[i] = Math.max(dp[i-1], dp[i-2]+count[i]*i);

java代码:

class Solution {
    public int deleteAndEarn(int[] nums) {
        int n = nums.length;
        if(n <= 1 ) return nums[0];
		int max = nums[0];
		for(int i : nums) {
			max = Math.max(max, i);
		}
		int[] count = new int[max+1];
		for(int i : nums) {
			count[i]++;
		}
		int[] dp = new int[max+1];
		dp[1] = count[1]*1;
		dp[2] = Math.max(dp[1], count[2]*2);
		for(int i = 3; i <= max; i++) {
			dp[i] = Math.max(dp[i-1], dp[i-2]+count[i]*i);
		}
		return dp[max];
    }
}

c++代码:

class Solution {
public:
    int deleteAndEarn(vector<int>& nums) {
        int n = nums.size();
        if( n == 1) return nums[0];
        int maxnum = nums[0];
        for(int i : nums) {
            maxnum = max(i,maxnum);
        }
        vector<int> count(maxnum+1),dp(maxnum+1);
        for(int i : nums) {
            count[i]++;
        }
        dp[1] = count[1];
        for(int i = 2; i <= maxnum; i++) {
            dp[i] = max(dp[i-1],dp[i-2] + count[i]*i);
        }
        return dp[maxnum];
        
    }
};

标签:count,java,nums,int,max,c++,maxnum,dp,LeetCode740
来源: https://blog.csdn.net/weixin_46100881/article/details/116419327