Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created March 16, 2025 17:17
Show Gist options
  • Save tatsuyax25/a63870df07af6f99f1ba0b7024acdba8 to your computer and use it in GitHub Desktop.
Save tatsuyax25/a63870df07af6f99f1ba0b7024acdba8 to your computer and use it in GitHub Desktop.
ou 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 c
/**
* @param {number[]} ranks
* @param {number} cars
* @return {number}
*/
var repairCars = function (ranks, cars) {
// Initialize the binary search range:
// 'left' represents the minimum possible time (1 minute).
// 'right' is the maximum possible time (if the slowest mechanic repairs all cars).
let left = 1;
let right = Math.min(...ranks) * cars * cars;
/**
* Helper function to determine if it's possible to repair all cars
* within the given time `mid`.
* @param {number} mid - The current time being tested.
* @return {boolean} - True if all cars can be repaired within `mid` time, otherwise false.
*/
function canRepairInTime(mid) {
let totalCars = 0; // Total number of cars repaired across all mechanics.
// Calculate the number of cars each mechanic can repair within `mid` time.
for (let rank of ranks) {
let count = Math.floor(Math.sqrt(mid / rank)); // Cars repaired by this mechanic.
totalCars += count;
// If the total cars repaired meet or exceed the required `cars`, return true early.
if (totalCars >= cars) return true;
}
// If the total cars repaired are less than required, return false.
return false;
}
// Binary search to find the minimum time.
while (left < right) {
let mid = Math.floor((left + right) / 2); // Calculate the midpoint of the current range.
// Check if it's feasible to repair all cars in `mid` time.
if (canRepairInTime(mid)) {
right = mid; // If feasible, reduce the upper limit (try to find a smaller time).
} else {
left = mid + 1; // If not feasible, increase the lower limit.
}
}
// The minimum time required to repair all cars is stored in 'left'.
return left;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment