Hard
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.
Example 1:
Input: power = 4, damage = [1,2,3,4], health = [4,5,6,8]
Output: 39
Explanation:
10 + 10 = 20
points.6 + 6 = 12
points.3
points.2 + 2 = 4
points.Example 2:
Input: power = 1, damage = [1,1,1,1], health = [1,2,3,4]
Output: 20
Explanation:
4
points.3 + 3 = 6
points.2 + 2 + 2 = 6
points.1 + 1 + 1 + 1 = 4
points.Example 3:
Input: power = 8, damage = [40], health = [59]
Output: 320
Constraints:
1 <= power <= 104
1 <= n == damage.length == health.length <= 105
1 <= damage[i], health[i] <= 104
import java.util.Arrays;
@SuppressWarnings("java:S1210")
public class Solution {
public long minDamage(int pw, int[] damage, int[] health) {
long res = 0;
long sum = 0;
for (int e : damage) {
sum += e;
}
Pair[] pairs = new Pair[damage.length];
for (int e = 0; e < damage.length; e++) {
pairs[e] = new Pair(damage[e], (health[e] + pw - 1) / pw);
}
Arrays.sort(pairs);
for (Pair pr : pairs) {
res += pr.val * sum;
sum -= pr.key;
}
return res;
}
static class Pair implements Comparable<Pair> {
int key;
int val;
Pair(int key, int val) {
this.key = key;
this.val = val;
}
@Override
public int compareTo(Pair p) {
return val * p.key - key * p.val;
}
}
}