LeetCode in Kotlin

2594. Minimum Time to Repair Cars

Medium

You are given an integer array ranks representing the ranks of some mechanics. ranksi is the rank of the ith mechanic. A mechanic with a rank r can repair n cars in r * n2 minutes.

You are also given an integer cars representing the total number of cars waiting in the garage to be repaired.

Return the minimum time taken to repair all the cars.

Note: All the mechanics can repair the cars simultaneously.

Example 1:

Input: ranks = [4,2,3,1], cars = 10

Output: 16

Explanation:

It can be proved that the cars cannot be repaired in less than 16 minutes.

Example 2:

Input: ranks = [5,1,8], cars = 6

Output: 16

Explanation:

It can be proved that the cars cannot be repaired in less than 16 minutes.

Constraints:

Solution

@Suppress("NAME_SHADOWING")
class Solution {
    fun repairCars(ranks: IntArray, cars: Int): Long {
        ranks.sort()
        var low: Long = 0
        var hi = Long.MAX_VALUE
        var ans: Long = -1
        while (low <= hi) {
            val mid = (low + hi) / 2
            if (isPossible(mid, ranks, cars)) {
                hi = mid - 1
                ans = mid
            } else {
                low = mid + 1
            }
        }
        return ans
    }

    private fun isPossible(target: Long, ranks: IntArray, cars: Int): Boolean {
        var cars = cars
        for (i in ranks.indices) {
            cars -= Math.sqrt((target / ranks[i]).toDouble()).toInt()
            if (cars <= 0) {
                return true
            }
        }
        return false
    }
}