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.
Input: ranks =[4,2,3,1], cars =10Output: 16Explanation:
- The first mechanic will repair two cars. The time required is4*2*2=16 minutes.- The second mechanic will repair two cars. The time required is2*2*2=8 minutes.- The third mechanic will repair two cars. The time required is3*2*2=12 minutes.- The fourth mechanic will repair four cars. The time required is1*4*4=16 minutes.It can be proved that the cars cannot be repaired in less than 16 minutes.
Example 2:
1
2
3
4
5
6
7
Input: ranks =[5,1,8], cars =6Output: 16Explanation:
- The first mechanic will repair one car. The time required is5*1*1=5 minutes.- The second mechanic will repair four cars. The time required is1*4*4=16 minutes.- The third mechanic will repair one car. The time required is8*1*1=8 minutes.It can be proved that the cars cannot be repaired in less than 16 minutes.
classSolution {
publiclongrepairCars(int[] ranks, int cars) {
long left = 1;
long right = (long) cars * cars * Arrays.stream(ranks).min().getAsInt();
long ans = right;
while (left <= right) {
long mid = left + (right - left) / 2;
if (canRepairWithinTime(ranks, cars, mid)) {
ans = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
return ans;
}
privatebooleancanRepairWithinTime(int[] ranks, int cars, long time) {
long repaired = 0;
for (int r : ranks) {
repaired += (long) Math.sqrt(time / r);
if (repaired >= cars) returntrue; // Early exit }
return repaired >= cars;
}
}