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