2594.js
/** ------------------------------------------------------------------------------
*
* 2594. Minimum Time to Repair Cars
* Topics: Array, Binary Search, Sorting
* https://leetcode.com/problems/minimum-time-to-repair-cars/description/?envType=daily-question&envId=2025-03-16
*
------------------------------------------------------------------------------ */
const repairCars = (ranks, cars) => {
// ranks.sort((a, b) => a - b);
let left = 1
let right = ranks[0] * Math.pow(cars, 2)
const isPossible = (time) => {
let total = 0
for (let i = 0; i < ranks.length; i++) {
const c = Math.floor(Math.sqrt(time / ranks[i]))
total += c
if (total >= cars) {
return true
}
}
return false
}
let ans = right
while (left <= right) {
const mid = Math.floor((left + right) / 2)
if (isPossible(mid)) {
ans = mid
right = mid - 1
} else {
left = mid + 1
}
}
return ans
}
console.log(repairCars([4, 2, 3, 1], 10))