Delete and Earn问题及解法

来源:互联网 发布:淘宝网千人千面 编辑:程序博客网 时间:2024/06/06 00:23

问题描述:

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.

示例:

Input: nums = [3, 4, 2]Output: 6Explanation: Delete 4 to earn 4 points, consequently 3 is also deleted.Then, delete 2 to earn 2 points. 6 total points are earned.
Input: nums = [2, 2, 3, 3, 3, 4]Output: 9Explanation: 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.

问题分析:

本题转换一下就跟House Robber差不多了,有点贪心的意思。统计每个数字的出现的和,例如,nums = [2,2,3,3,3,4]中,2的和是4,3的和是9,4的和是4.

然后组成新的数组[2,3,4],这些数字就代表着是否相邻,2,3相邻,3,4相邻,这时再利用house robber的解法即可求解。


过程详见代码:

class Solution {public:    int deleteAndEarn(vector<int>& nums) {        vector<int> res(10001, 0);for (auto n : nums){res[n] += n;}vector<int> dp(10001, 0);dp[1] = res[1];for (int i = 2; i <= 10000; i++){dp[i] = max(dp[i - 1], dp[i - 2] + res[i]);}return dp[10000];    }};


原创粉丝点击