LeetCode 3186: Maximum Total Damage With Spell Casting Solution

Master LeetCode problem 3186 (Maximum Total Damage With Spell Casting), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

3186. Maximum Total Damage With Spell Casting

Problem Explanation

Explanation

To maximize the total damage the magician can cast, we can sort the array and then iterate through the sorted array while keeping track of the total damage. We can use a hashmap to keep track of the maximum total damage we can achieve for each spell power.

  1. Sort the given array power.
  2. Initialize a hashmap dp to store the maximum total damage for each spell power.
  3. Iterate through the sorted array and update the maximum total damage for each spell power by considering the possibility of including or excluding the current spell.
  4. Return the maximum total damage stored in the hashmap.

Time complexity: O(nlogn) where n is the number of elements in the input array. Space complexity: O(n) for the hashmap.

Solution Code

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

class Solution {
    public int maxTotalDamage(int[] power) {
        Arrays.sort(power);
        Map<Integer, Integer> dp = new HashMap<>();
        for (int p : power) {
            dp.put(p, Math.max(dp.getOrDefault(p, 0), dp.getOrDefault(p - 2, 0) + p));
        }
        int maxDamage = 0;
        for (int value : dp.values()) {
            maxDamage = Math.max(maxDamage, value);
        }
        return maxDamage;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3186 (Maximum Total Damage With Spell Casting)?

This page provides optimized solutions for LeetCode problem 3186 (Maximum Total Damage With Spell Casting) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 3186 (Maximum Total Damage With Spell Casting)?

The time complexity for LeetCode 3186 (Maximum Total Damage With Spell Casting) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3186 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3186 in Java, C++, or Python.

Back to LeetCode Solutions