Minimum Amount of Damage Dealt to Bob

Ah, the classic dilemma of dealing with enemies while trying to minimize damage—sounds like a typical Tuesday for Bob! Imagine Bob as that friend who always seems to attract trouble, like a magnet for bad decisions. Now, Bob has a power level (let’s say he’s been hitting the gym) and a bunch of enemies who are just waiting to take him down. The goal? To figure out how to deal with these enemies in a way that minimizes the total damage Bob takes.

Problem Description

Bob is in a bit of a pickle. He has a power level that allows him to deal damage to enemies, but those enemies are not just sitting there waiting to be defeated. They are dealing damage back to Bob while he’s busy trying to take them down. The challenge is to determine the order in which Bob should take down these enemies to minimize the total damage he receives.

Code Solution


from dataclasses import dataclass

@dataclass(frozen=True)
class Enemy:
    damage: int
    timeTakenDown: int

class Solution:
    def minDamage(self, power: int, damage: list[int], health: list[int]) -> int:
        ans = 0
        sumDamage = sum(damage)
        enemies = [Enemy(d, (h + power - 1) // power)
                   for d, h in zip(damage, health)]

        enemies.sort(key=lambda x: -x.damage / x.timeTakenDown)

        for enemy in enemies:
            ans += sumDamage * enemy.timeTakenDown
            sumDamage -= enemy.damage

        return ans

Approach Explanation

The code begins by defining an Enemy class to encapsulate the damage and time taken to defeat each enemy. The minDamage function calculates the total damage Bob will take based on the order in which he defeats the enemies. The enemies are sorted based on their damage-to-time ratio, ensuring that Bob takes down the most dangerous enemies first. This greedy approach minimizes the total damage Bob incurs.

Time and Space Complexity

  • Time Complexity: O(n log n), where n is the number of enemies. This is due to the sorting step.
  • Space Complexity: O(n), for storing the list of enemies.

Real-World Example

Imagine Bob is at a party, and he’s trying to avoid getting into a fight with the rowdy guests. Each guest has a different level of annoyance (damage) and takes a different amount of time to calm down (health). Bob needs to figure out which guests to deal with first to minimize the overall chaos (damage) he experiences. By prioritizing the most annoying guests, Bob can enjoy the party with minimal hassle!

Similar Problems

Navigation Links