Minimum Amount of Damage Dealt to Bob - Problem

You are given an integer power and two integer arrays damage and health, both having length n.

Bob has n enemies, where enemy i will deal Bob damage[i] points of damage per second while they are alive (i.e. health[i] > 0).

Every second, after the enemies deal damage to Bob, he chooses one of the enemies that is still alive and deals power points of damage to them.

Determine the minimum total amount of damage points that will be dealt to Bob before all n enemies are dead.

Input & Output

Example 1 — Basic Case
$ Input: power = 10, damage = [10,4,15], health = [80,20,40]
Output: 138
💡 Note: Enemy ratios: 10/8=1.25, 4/2=2.0, 15/4=3.75. Attack order [2,1,0] gives minimum damage of 138.
Example 2 — Equal Ratios
$ Input: power = 5, damage = [5,10], health = [10,20]
Output: 30
💡 Note: Both enemies have ratio 5/2=2.5. Either order works, total damage is 30.
Example 3 — Single Enemy
$ Input: power = 20, damage = [15], health = [30]
Output: 30
💡 Note: Only one enemy: takes 2 turns to kill, deals 15 damage per turn, total 30.

Constraints

  • 1 ≤ power ≤ 104
  • 1 ≤ n ≤ 105
  • 1 ≤ damage[i], health[i] ≤ 104

Visualization

Tap to expand
Minimum Damage Dealt to Bob INPUT power = 10 Enemies Enemy 0 damage=10, health=80 8 sec to kill Enemy 1 damage=4, health=20 2 sec to kill Enemy 2 damage=15, health=40 4 sec to kill time[i] = ceil(health[i]/power) Seconds needed to kill enemy ALGORITHM STEPS 1 Calculate Priority ratio = damage[i] / time[i] 2 Sort by Ratio (DESC) Higher ratio = kill first Enemy Ratio Order E2 15/4=3.75 1st E1 4/2=2.00 2nd E0 10/8=1.25 3rd 3 Calculate Damage Sum remaining dmg * time 4 Accumulate Total Each kill reduces future Order: E2 --> E1 --> E0 Minimizes total damage! FINAL RESULT Optimal Kill Sequence Kill E2 (4 sec) All 3 deal dmg: (10+4+15)*4 = 116 damage Kill E1 (2 sec) E0,E1 deal dmg: (10+4)*2 = 28 damage Kill E0 (8 sec) Only E0 deals dmg: 10*8 = 80 damage - Wait! Recalc: 116 - 80 = 36 diff Optimal: 116 + 14 + 8 = 138 Total Damage 138 Key Insight: Greedy approach: Kill enemies with highest (damage/kill_time) ratio first. This minimizes the cumulative damage by removing high-damage-per-second enemies quickly, reducing the total damage dealt while other enemies are still alive. TutorialsPoint - Minimum Amount of Damage Dealt to Bob | Greedy - Optimal Priority Order
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
32.0K Views
Medium Frequency
~35 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen