LeetCode-in-Java

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

public class Solution {
    public long repairCars(int[] ranks, int cars) {
        long low = 0;
        long high = 100000000000000L;
        long pivot;
        while (low <= high) {
            pivot = low + (high - low) / 2;
            if (canRepairAllCars(ranks, cars, pivot)) {
                high = pivot - 1;
            } else {
                low = pivot + 1;
            }
        }
        return low;
    }

    private boolean canRepairAllCars(int[] ranks, int cars, long totalMinutes) {
        int repairedCars = 0;
        for (int i = 0; i < ranks.length && repairedCars < cars; i++) {
            repairedCars += (int) Math.sqrt((double) totalMinutes / ranks[i]);
        }
        return repairedCars >= cars;
    }
}