740. Delete and Earn

题目

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 everyelement 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.

分析

这是一道动态规划的题目,不过较最简单的动态规划复杂一点的就是它需要对相邻的数字进行必要的处理。因为当我们考虑取一个数字得分的时候会让取其相邻数字得分的情况下的分值改变。因此在此题我使用了两次的动态规划。(对不相领的数字串和相邻数字串的动态规划)
首先我把原先输入乱序的数字排序,然后用一个map将数字对应的分值保存下来,并新建一个vector来记录各个数字,然后首先是外层的处理,当此数字与前一数字不相邻时,结果直接加上它对应的分值,如果不是则对所有相邻数字进行动态规划。
代码如下:

代码

class Solution {
public:
	int deleteAndEarn(vector<int>& nums) {
		if (!nums.empty()) {
			sort(nums.begin(), nums.end());
			map<int, int> cost;
			vector<int> single;
			for (int i = 0; i < nums.size(); ++i) {
				int count = 1;
				while (i + 1 != nums.size() && nums[i] == nums[i + 1]) {
					count++;
					i++;
				}
				cost[nums[i]] = count * nums[i];
				single.push_back(nums[i]);
			}
			vector<int> result(single.size(), 0);
			result[0] = cost[single[0]];
			for (int i = 1; i < single.size(); ++i) {
				if (single[i - 1] + 1 != single[i]) {
					if (i + 1 != single.size() && single[i + 1] - 1 == single[i]) {
						result[i] = cost[single[i]];
					}
					else {
						result[i] = result[i - 1] + cost[single[i]];
					}
				}
				else {
					int index = i;
					int t_max;
					int t_count = 2;
					while (i != single.size() && single[i] == single[i - 1] + 1) {
						if (t_count == 2) {
							result[i] = cost[single[i]];
						}
						else {
							if (t_count > 3) {
								result[i] = cost[single[i]] + max(result[i - 2], result[i - 3]);
							}
							else {
								result[i] = result[i - 2] + cost[single[i]];
							}
						}
						++i;
						++t_count;
					}
						--i;
					result[i] = max(result[i], result[i - 1]);
					if (index != 1) {
						result[i] += result[index-2];
					}
				}
			}
			return max(result[single.size() - 1], result[single.size() - 2]);
		}
		else {
			return 0;
		}
		
	}
};




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值