Delete and Earn - Problem
Delete and Earn is a strategic optimization problem where you need to maximize points by carefully choosing which numbers to delete from an array.
๐ฏ The Challenge: You're given an integer array
Goal: Return the maximum number of points you can earn by applying this operation optimally.
Example: With array
๐ฏ The Challenge: You're given an integer array
nums. Each time you pick a number nums[i], you earn nums[i] points, but there's a catch - you must also delete all occurrences of nums[i] - 1 and nums[i] + 1 from the array!Goal: Return the maximum number of points you can earn by applying this operation optimally.
Example: With array
[3, 4, 2], if you pick 4 (earning 4 points), you must delete all 3s and 5s. This strategic constraint makes the problem similar to the classic House Robber problem! Input & Output
example_1.py โ Basic Case
$
Input:
[3, 4, 2]
โบ
Output:
6
๐ก Note:
You can perform operations: take 4 (earning 4 points, must delete 3s and 5s), then take 2 (earning 2 points, must delete 1s and 3s). Total: 4 + 2 = 6 points.
example_2.py โ Duplicates
$
Input:
[2, 2, 3, 3, 3, 4]
โบ
Output:
9
๐ก Note:
Take all three 3s (earning 3+3+3 = 9 points). This forces deletion of all 2s and 4s, but 9 > 4+4 = 8, so this is optimal.
example_3.py โ Single Element
$
Input:
[1]
โบ
Output:
1
๐ก Note:
Only one element exists, so take it for 1 point. No adjacent elements to worry about.
Constraints
- 1 โค nums.length โค 2 ร 104
- 1 โค nums[i] โค 104
- Follow-up: Can you solve it in O(n) time?
Visualization
Tap to expand
Understanding the Visualization
1
Survey the Cave
Count how many chests of each number exist and calculate total treasure per number
2
Apply the Ancient Rule
Use House Robber logic: for each number, decide whether to take it or skip it based on maximum benefit
3
Make Strategic Choices
Adjacent numbers create conflicts - choose the combination that maximizes total treasure
4
Collect Maximum Gold
The DP solution ensures we get the theoretical maximum possible treasure
Key Takeaway
๐ฏ Key Insight: Transform the problem into House Robber by grouping identical numbers and applying the constraint that adjacent numbers cannot both be selected. This reduces a complex optimization problem into a well-known DP pattern with O(n) solution!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code