#3273

Minimum Amount of Damage Dealt to Bob

Hard
ArrayGreedySortingGreedy AlgorithmsSorting
LeetCode ↗

Approaches

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

Intuition

Time O(n log n)Space O(n)

The optimal approach uses a greedy strategy: prioritize attacking enemies based on their damage output and health. By sorting enemies, we can minimize the damage dealt to Bob.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a list of enemies with their damage and health.
  2. 2Step 2: Sort the enemies based on the ratio of damage to health (damage[i] / (health[i] / power)).
  3. 3Step 3: Simulate the battle by attacking the sorted enemies in order until all are defeated, calculating the total damage to Bob.
solution.py9 lines
1def min_damage_optimal(power, damage, health):
2    enemies = sorted(zip(damage, health), key=lambda x: x[0] / (x[1] / power))
3    total_damage = 0
4    time = 0
5    for d, h in enemies:
6        time_to_kill = (h + power - 1) // power
7        total_damage += time_to_kill * d
8        time += time_to_kill
9    return total_damage

Complexity note: The time complexity is O(n log n) due to sorting the enemies, and the space complexity is O(n) for storing the enemy data.

  • 1Prioritize attacking enemies based on their damage output and health to minimize total damage.
  • 2Sorting enemies helps in making optimal decisions on which enemy to attack first.

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