#740
Delete and Earn
MediumArrayHash TableDynamic ProgrammingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + k), where k is the maximum number in nums. |
| Space | O(1) | O(k) |
💡
Intuition
Time O(n + k), where k is the maximum number in nums.Space O(k)
Instead of exploring all subsets, we can use dynamic programming to keep track of the maximum points we can earn by either taking or skipping each number. This reduces the problem to a linear scan of the numbers.
⚙️
Algorithm
3 steps- 1Step 1: Count the frequency of each number in the input array.
- 2Step 2: Create a points array where points[i] = i * frequency of i.
- 3Step 3: Use dynamic programming to calculate the maximum points by deciding whether to take or skip each number based on the previous calculations.
solution.py12 lines
1def delete_and_earn(nums):
2 if not nums:
3 return 0
4 max_num = max(nums)
5 points = [0] * (max_num + 1)
6 for num in nums:
7 points[num] += num
8 earn = [0] * (max_num + 1)
9 earn[1] = points[1]
10 for i in range(2, max_num + 1):
11 earn[i] = max(earn[i - 1], earn[i - 2] + points[i])
12 return earn[max_num]ℹ
Complexity note: The time complexity is linear because we only traverse the nums array and the points array, while the space complexity is determined by the maximum number in the input array.
- 1Taking all instances of a number is optimal when choosing that number.
- 2Dynamic programming helps in making optimal choices based on previous states.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.