LeetCode 740. Delete and Earn

Question

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
2
3
4
5
6
7
8
9
10
11
12
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.

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.

Solution

一开始看这个题目,感觉是搜索的题目然后使用记忆化优化,尝试去选择所有的不同的组合,但是这样删除元素以及选择遍历顺序的时候导致时间复杂度是指数级别。所以,经过看了discussion之后发现,这个题原来可以处理为house robber问题。因为这里的需要删除nums[i] - 1 或者 nums[i] + 1。则和之前的题一样,无法取相邻的数值。只需要将原来的数组处理为相同元素的和,然后使用bucket sort,从前往后遍历一遍,分别为取当前值和不取当前值的操作即可。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// time: O(n) space:O(n)
public int deleteAndEarn(int[] nums) {
// 利用桶排序构造,之后按照无法取相邻的情况进行操作
if (nums == null || nums.length == 0) return 0;
int n = 10001;
int[] values = new int[n];
for (int num : nums)
values[num] += num;

int skip = 0, take = 0;
for (int i = 0; i < n; i++) {
int temp = take;
take = Math.max(take, skip + values[i]);
skip = Math.max(skip, temp);
}
return Math.max(take, skip);
}

Reference