Minimum Time to Repair Cars Problem
Description
LeetCode Problem 2594.
You are given an integer array ranks representing the ranks of some mechanics. ranks_i is the rank of the i^th mechanic. A mechanic with a rank r can repair n cars in r * n^2 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:
- The first mechanic will repair two cars. The time required is 4 * 2 * 2 = 16 minutes.
- The second mechanic will repair two cars. The time required is 2 * 2 * 2 = 8 minutes.
- The third mechanic will repair two cars. The time required is 3 * 2 * 2 = 12 minutes.
- The fourth mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes.
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:
- The first mechanic will repair one car. The time required is 5 * 1 * 1 = 5 minutes.
- The second mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes.
- The third mechanic will repair one car. The time required is 8 * 1 * 1 = 8 minutes.
It can be proved that the cars cannot be repaired in less than 16 minutes.
Constraints:
1 <= ranks.length <= 10^51 <= ranks[i] <= 1001 <= cars <= 10^6
Solution
Approach: Binary Search
The more time we have, the more cars get repaired, so we can binary search the minimum time. The upper bound is ranks[0] * cars * cars (the first mechanic alone repairing everything).
For a time t, a mechanic with rank r repairs the largest k with r * k * k <= t, that is floor(sqrt(t / r)) cars. If the total over all mechanics is at least cars, then t is enough and we move the right bound to t; otherwise we move the left bound to t + 1. Return the left bound.
The time complexity is O(n log M) and the space complexity is O(1), where M is the upper bound.
from math import sqrt
class Solution:
def repairCars(self, ranks: List[int], cars: int) -> int:
def check(t: int) -> bool:
return sum(int(sqrt(t // r)) for r in ranks) >= cars
left, right = 0, ranks[0] * cars * cars
while left < right:
mid = (left + right) >> 1
if check(mid):
right = mid
else:
left = mid + 1
return left