Approach
Sorting and greedy selection
For Minimum Amount of Damage Dealt to Bob, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 40 lines of Java from the credited upstream file 3273.java.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Enemy {2 public int damage;3 public int timeTakenDown;4 public Enemy(int damage, int timeTakenDown) {5 this.damage = damage;6 this.timeTakenDown = timeTakenDown;7 }8}9 10class Solution {11 public long minDamage(int power, int[] damage, int[] health) {12 long ans = 0;13 long sumDamage = Arrays.stream(damage).asLongStream().sum();14 Enemy[] enemies = new Enemy[damage.length];15 16 for (int i = 0; i < damage.length; ++i)17 enemies[i] = new Enemy(damage[i], (health[i] + power - 1) / power);18 19 20 21 22 23 24 25 26 27 Arrays.sort(enemies,28 (a, b)29 -> Double.compare((double) b.damage / b.timeTakenDown,30 (double) a.damage / a.timeTakenDown));31 32 for (final Enemy enemy : enemies) {33 ans += sumDamage * enemy.timeTakenDown;34 sumDamage -= enemy.damage;35 }36 37 return ans;38 }39}40