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: 4
💡 Note: We can cast the spell with damage 4. If we cast spells with damage 1, we get total 2 but cannot cast damage 3 or 4. Casting damage 3 gives us 3. Casting damage 4 gives us 4, which is maximum.
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 CastingInput spells: [1, 1, 3, 4]1134Constraint: If we cast damage X, we cannot cast X-2, X-1, X+1, X+2If we cast damage 4: blocks damage 2,3,5,6If we cast damage 3: blocks damage 1,2,4,5✓ Best choice: Cast spell with damage 4Maximum Total Damage: 4
Understanding the Visualization
1
Input
Array of spell damage values with constraint rules
2
Constraint
Casting spell with damage X blocks X±1 and X±2
3
Output
Maximum total damage possible
Key Takeaway
🎯 Key Insight: Group identical spells and use dynamic programming with house robber pattern, considering constraint distance of 2
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