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 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
๐Ÿดโ€โ˜ ๏ธ The Treasure Hunter's Cave ๐Ÿดโ€โ˜ ๏ธMagic Rule: Opening chest X destroys chests X-1 and X+1Choose wisely to maximize your treasure!Chest 2๐Ÿ’ฐ4 goldChest 3๐Ÿ’Ž9 goldChest 4๐Ÿ’ฐ4 goldโšกโšกStrategic Decision TreeTake Chest 3: 9 goldDestroys Chests 2 & 4: -8 goldNet Gain: 9 gold๐ŸŽฏ Optimal Strategy Found!Take Chest 3 for maximum 9 gold๐Ÿ’ก DP Magic: dp[i] = max(dp[i-1], dp[i-2] + treasure[i])
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!
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
78.4K Views
High Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen