Maximum Total Damage With Spell Casting Problem
Description
LeetCode Problem 3186.
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.
Example 1:
Input: power = [1,1,3,4]
Output: 6
Explanation:
The maximum possible damage of 6 is produced by casting spells 0, 1, 3 with damage 1, 1, 4.
Example 2:
Input: power = [7,1,6,6]
Output: 13
Explanation:
The maximum possible damage of 13 is produced by casting spells 1, 2, 3 with damage 1, 6, 6.
Constraints:
1 <= power.length <= 10^51 <= power[i] <= 10^9
Solution
Approach: Sorting + Binary Search + Dynamic Programming
Sort power and count how often each damage value occurs. Using a value x forbids x - 2 to x + 2, and all copies of x can be used together, so for each index i precompute nxt[i], the first index whose value is greater than x + 2 (binary search). Let f[i] be the best total using the elements from index i on. Either skip all copies of x and go to i + cnt[x], or take them all and go to nxt[i]: f[i] = max(f[i + cnt[x]], x * cnt[x] + f[nxt[i]]). The answer is f[0]; computing i from right to left avoids deep recursion.
Complexity: O(n log n) time and O(n) space.
from bisect import bisect_right
from collections import Counter
class Solution:
def maximumTotalDamage(self, power: List[int]) -> int:
n = len(power)
cnt = Counter(power)
power.sort()
nxt = [bisect_right(power, x + 2, lo=i + 1) for i, x in enumerate(power)]
f = [0] * (n + 1)
for i in range(n - 1, -1, -1):
a = f[min(n, i + cnt[power[i]])]
b = power[i] * cnt[power[i]] + f[nxt[i]]
f[i] = max(a, b)
return f[0]