Maximum Total Damage With Spell Casting - Problem

A magician has various spells. You are given an array power, where each element represents the damage of a spell. Multiple spells can have the same damage value.

It is a known fact that if a magician decides to cast a spell with a damage of power[i], they cannot cast any spell with a damage of power[i] - 2, power[i] - 1, power[i] + 1, or power[i] + 2.

Each spell can be cast only once. Return the maximum possible total damage that a magician can cast.

Input & Output

Example 1 — Basic Case
$ Input: power = [1,1,3,4]
Output: 6
💡 Note: We can cast both spells with damage 1 and the spell with damage 4. The spell with damage 4 conflicts with damage 2,3,5,6 (which don't exist or can't be cast), so we can cast damage 1 twice and damage 4 once. Total = 1 + 1 + 4 = 6. We cannot include damage 3 because it conflicts with damage 1 and 4.
Example 2 — Multiple Same Values
$ Input: power = [7,1,6,6]
Output: 13
💡 Note: We can cast both spells with damage 6 and the spell with damage 1. Total = 6 + 6 + 1 = 13. We cannot include damage 7 because it conflicts with damage 6.
Example 3 — All Consecutive
$ Input: power = [1,2,3,4,5]
Output: 5
💡 Note: All damages are consecutive and conflict with each other. The best strategy is to pick the single highest damage spell: 5.

Constraints

  • 1 ≤ power.length ≤ 105
  • 1 ≤ power[i] ≤ 109

Visualization

Tap to expand
Maximum Total Damage With Spell Casting INPUT power = [1, 1, 3, 4] 1 i=0 1 i=1 3 i=2 4 i=3 Spell Constraints If casting power[i], cannot cast: power[i]-2, power[i]-1 power[i]+1, power[i]+2 Example: If cast damage=3 Cannot cast: 1, 2, 4, 5 (conflicts with 1,1 and 4) ALGORITHM STEPS 1 Sort & Group Group same damage values Groups: {1:2, 3:1, 4:1} 2 Define DP State dp[i] = max damage using first i unique damage values 3 DP Transition For each unique damage d: skip or take (find valid j) 4 Calculate Options Take 1s: 1*2 = 2 Take 4: 4*1 = 4 Cannot take both (conflict) DP Choices: Option A: 1+1 = 2 Option B: 4 = 4 [BEST] FINAL RESULT Optimal Choice: Cast: 4 Skipped Spells: 1 1 3 3 conflicts with 4 (diff=1) 1s conflict with 3 (diff=2) Maximum Damage 4 OK Key Insight: This is a variant of the House Robber problem. We use Dynamic Programming where for each unique damage value, we decide to either skip it or take all instances of it. When taking damage d, we must find the nearest valid previous damage (d-3 or less) and add to its DP value. TutorialsPoint - Maximum Total Damage With Spell Casting | Optimal Solution (Dynamic Programming)
Asked in
Google 15 Meta 12 Amazon 10
23.4K Views
Medium Frequency
~25 min Avg. Time
890 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