740. Delete and Earn
2017-12-18 16:47
465 查看
问题描述:
Given an array
In each operation, you pick any
After, you must delete every element equal to
You start with 0 points. Return the maximum number of points you can earn by applying such operations.
给一个数组,每次选择一个数nums[i],可获得nums[i]的分数,同时要抛弃nums[i]-1和nums[i]+1的数,求最大得分
问题解决:
定义一个数组n,n[i]表示数值为i的数在数组中有多少个
定义一个数组point,point[i]表示从数值0到数值i遵循以上规则选择抛弃可获得的最大分数,有以下递推式
point[i] = Math.max(point[i-1], point[i-2] + i * n[i])
代码如下:
class Solution {
public:
int deleteAndEarn(vector<int>& nums) {
//若长度为0,返回0
if(nums.size() == 0) return 0;
//定义数组n并初始化
vector<int> n(10001,0);
int i;
//循环算出每个数值的个数
for(i = 0; i < nums.size(); i++) n[nums[i]]++;
//定义数组point
vector<int> points(10001,0);
points[1] = n[1];
//根据递推式算出数值0到i可获得的最大分数
for(i = 2; i < 10001; i++) {
points[i] = points[i-1] > points[i-2]+i*n[i] ? points[i-1] : points[i-2]+i*n[i];
}
return points[10000];
}
};
Given an array
numsof 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] - 1or
nums[i] + 1.
You start with 0 points. Return the maximum number of points you can earn by applying such operations.
给一个数组,每次选择一个数nums[i],可获得nums[i]的分数,同时要抛弃nums[i]-1和nums[i]+1的数,求最大得分
问题解决:
定义一个数组n,n[i]表示数值为i的数在数组中有多少个
定义一个数组point,point[i]表示从数值0到数值i遵循以上规则选择抛弃可获得的最大分数,有以下递推式
point[i] = Math.max(point[i-1], point[i-2] + i * n[i])
代码如下:
class Solution {
public:
int deleteAndEarn(vector<int>& nums) {
//若长度为0,返回0
if(nums.size() == 0) return 0;
//定义数组n并初始化
vector<int> n(10001,0);
int i;
//循环算出每个数值的个数
for(i = 0; i < nums.size(); i++) n[nums[i]]++;
//定义数组point
vector<int> points(10001,0);
points[1] = n[1];
//根据递推式算出数值0到i可获得的最大分数
for(i = 2; i < 10001; i++) {
points[i] = points[i-1] > points[i-2]+i*n[i] ? points[i-1] : points[i-2]+i*n[i];
}
return points[10000];
}
};
相关文章推荐
- 740[Medium]:Delete and Earn
- 740. Delete and Earn
- 【第十五周】740. Delete and Earn
- LWC 61:740. Delete and Earn
- 740. Delete and Earn
- 740. Delete and Earn
- 740. Delete and Earn
- 740. Delete and Earn
- 740. Delete and Earn
- Leetcode刷题:740. Delete and Earn
- 740. Delete and Earn
- 740. Delete and Earn
- 740. Delete and Earn
- LeetCode | 740. Delete and Earn
- 再从萌新开始-Leetcode每日题解-740. Delete and Earn
- 算法题目--Delete and Earn
- Leetcode 740.Delete and Earn(第十六周作业)
- week17-leetcode #740-DeleteandEarn
- LeetCode740. Delete and Earn
- leetcode练习 Delete and Earn