您的位置:首页 > 其它

Delete and Earn

2018-01-18 00:00 417 查看
问题:

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.

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.

Note:

The length of
nums
is at most
20000
.

Each element
nums[i]
is an integer in the range
[1, 10000]
.

解决:

【题意】

给定整数数组nums,执行如下操作:

挑选任意数字nums[i],得到nums[i]分,同时需要删除所有等于nums[i] - 1和nums[i] + 1的整数。

求最大得分。

① 动态规划。

House Robber类似,对于每一个数字,我们都有两个选择,拿或者不拿。如果我们拿了当前的数字,我们就不能拿之前的数字(如果我们从小往大遍历就不需要考虑后面的数字),那么当前的积分就是不拿前面的数字的积分加上当前数字之和。如果我们不拿当前的数字,那么对于前面的数字我们既可以拿也可以不拿,于是当前的积分就是拿前面的数字的积分和不拿前面数字的积分中的较大值。

take和skip分别表示拿与不拿上一个数字,takei和skipi分别表示拿与不拿当前数字。

class Solution { //18ms
public int deleteAndEarn(int[] nums) {
int[] sums = new int[10001];
int take = 0;
int skip = 0;
for (int n : nums){
sums
+= n;
}
for (int i = 0;i < 10001;i ++){
int takei = skip + sums[i];
int skipi = Math.max(skip,take);
take = takei;
skip = skipi;
}
return Math.max(skip,take);
}
}

② sums[i]表示到当前值为止的最大值。

class Solution { //11ms
public int deleteAndEarn(int[] nums) {
int[] sums = new int[10001];
for (int n : nums){
sums
+= n;
}
for (int i = 2;i < 10001;i ++){
sums[i] = Math.max(sums[i - 1],sums[i - 2] + sums[i]);
}
return sums[10000];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: