#3186

Maximum Total Damage With Spell Casting

Medium
ArrayHash TableTwo PointersBinary SearchDynamic ProgrammingSortingCountingHash MapDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + k)
Space
O(1)
O(k)
💡

Intuition

Time O(n + k)Space O(k)

The optimal solution uses dynamic programming to build up the maximum damage possible by considering each spell's damage and the constraints on casting. This avoids the combinatorial explosion of subsets.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the frequency of each damage value in the power array.
  2. 2Step 2: Use a dynamic programming array where dp[i] represents the maximum damage possible using spells up to damage i.
  3. 3Step 3: For each unique damage value, update the dp array based on whether we include that damage or not, considering the constraints.
solution.py12 lines
1from collections import Counter
2
3def max_damage_optimal(power):
4    count = Counter(power)
5    max_damage = 0
6    dp = [0] * (max(count.keys()) + 1)
7    for damage in range(len(dp)):
8        if damage in count:
9            dp[damage] = max(dp[damage - 1], (dp[damage - 2] if damage >= 2 else 0) + damage * count[damage])
10        else:
11            dp[damage] = dp[damage - 1]
12    return dp[-1]

Complexity note: The time complexity is O(n + k), where n is the number of spells and k is the range of unique damage values. The space complexity is O(k) for the dp array and the count map.

  • 1Casting spells with the same damage maximizes total damage.
  • 2Avoiding adjacent damage values is crucial for optimal casting.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.