LeetCode in Kotlin

3273. Minimum Amount of Damage Dealt to Bob

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:

Example 2:

Input: power = 1, damage = [1,1,1,1], health = [1,2,3,4]

Output: 20

Explanation:

Example 3:

Input: power = 8, damage = [40], health = [59]

Output: 320

Constraints:

Solution

class Solution {
    fun minDamage(pw: Int, damage: IntArray, health: IntArray): Long {
        var res: Long = 0
        var sum: Long = 0
        for (e in damage) {
            sum += e.toLong()
        }
        val pairs = arrayOfNulls<Pair>(damage.size)
        for (e in damage.indices) {
            pairs[e] = Pair(damage[e], (health[e] + pw - 1) / pw)
        }
        pairs.sort()
        for (pr in pairs) {
            res += pr!!.`val` * sum
            sum -= pr.key.toLong()
        }
        return res
    }

    internal class Pair(var key: Int, var `val`: Int) : Comparable<Pair> {
        override fun compareTo(p: Pair): Int {
            return `val` * p.key - key * p.`val`
        }
    }
}