Delete and Earn - Problem

You are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times:

Pick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1.

Return the maximum number of points you can earn by applying the above operation some number of times.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,4,2]
Output: 6
💡 Note: Delete 4 to earn 4 points (removes 3). Then delete 2 to earn 2 points. Total: 4 + 2 = 6
Example 2 — Multiple Same Values
$ Input: nums = [2,2,3,3,3,4]
Output: 9
💡 Note: Delete all 3's to earn 3×3=9 points (removes all 2's and 4's). This is better than taking 2's and 4's for 2×2+4=8 points
Example 3 — Single Element
$ Input: nums = [1]
Output: 1
💡 Note: Only one element, so delete it to earn 1 point

Constraints

  • 1 ≤ nums.length ≤ 2×104
  • 1 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Delete and Earn: Input → Process → OutputINPUT: [3, 4, 2]342PROCESS: Optimal Deletion StrategyOption 1: Delete 4 → Earn 4, Remove 3Then delete 2 → Earn 2Total: 4 + 2 = 6 ✓Option 2: Delete 3 → Earn 3, Remove 2,4No more deletions possibleTotal: 36OUTPUT: Maximum Points = 6
Understanding the Visualization
1
Input Array
Array with numbers that can be deleted for points
2
Delete Rule
Deleting nums[i] removes all nums[i]±1 values
3
Maximize Points
Choose optimal deletion sequence for maximum total
Key Takeaway
🎯 Key Insight: Transform to House Robber by grouping same numbers - adjacent values can't both be taken
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
158.0K Views
Medium Frequency
~25 min Avg. Time
3.2K 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