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 - Dynamic Programming INPUT nums = [3, 4, 2] 3 i=0 4 i=1 2 i=2 Pick a number to earn points Delete adjacent values (+/-1) Count Array: 0 val=1 2 val=2 3 val=3 4 val=4 0 val=5 points[i] = i * count[i] [0, 2, 3, 4, 0] ALGORITHM STEPS 1 Build Points Array points[i] = i * frequency 2 Define DP State dp[i] = max points using 0..i 3 DP Transition dp[i] = max(dp[i-1], dp[i-2] + points[i]) 4 Compute DP Table DP Computation: i: 0 1 2 3 4 pts: 0 0 2 3 4 dp: 0 0 2 3 6 dp[4] = max(3, 2+4) = 6 Pick 2 and 4 (skip 3) FINAL RESULT Optimal Selection: 2 PICK 3 SKIP 4 PICK Points earned: 2 + 4 = 6 Output: 6 OK - Maximum Points! Cannot pick both 3 and 4 (adjacent values) Key Insight: This problem reduces to House Robber! When you pick value k, you must skip k-1 and k+1. Build a points array where points[i] = i * count(i), then apply DP: at each position, choose to take current + dp[i-2] or skip with dp[i-1]. Time: O(n + max), Space: O(max). TutorialsPoint - Delete and Earn | Dynamic Programming Approach
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