Problem:
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:
1 2 3 4 5 |
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:
1 2 3 4 5 6 |
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 most20000
. - Each element
nums[i]
is an integer in the range[1, 10000]
.
Idea:
Reduce the problem to House Robber Problem
Key observations: If we take nums[i]
- We can safely take all of its copies.
- We can’t take any of copies of nums[i – 1] and nums[i + 1]
This problem is reduced to 198 House Robber.
Houses[i] has all the copies of num whose value is i.
[3 4 2] -> [0 2 3 4], rob([0 2 3 4]) = 6
[2, 2, 3, 3, 3, 4] -> [0 2*2 3*3 4], rob([0 2*2 3*3 4]) = 9
Time complexity: O(n+r) reduction + O(r) solving rob = O(n + r)
Space complexity: O(r)
r = max(nums) – min(nums) + 1
Time complexity: O(n + r)
Space complexity: O(r)
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// Author: Huahua // Runtime: 6 ms class Solution { public: int deleteAndEarn(vector<int>& nums) { if (nums.empty()) return 0; const auto range = minmax_element(nums.begin(), nums.end()); const int l = *(range.first); const int r = *(range.second); vector<int> points(r - l + 1, 0); for (const int num : nums) points[num - l] += num; return rob(points); } private: // From LeetCode 198. House Robber int rob(const vector<int>& nums) { int dp2 = 0; int dp1 = 0; for (int i = 0; i < nums.size() ; ++i) { int dp = max(dp2 + nums[i], dp1); dp2 = dp1; dp1 = dp; } return dp1; } }; |
Related Problem:
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment