Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created December 1, 2025 18:46
Show Gist options
  • Select an option

  • Save tatsuyax25/6073a2044bd6b57b3f129d7ecb61843e to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/6073a2044bd6b57b3f129d7ecb61843e to your computer and use it in GitHub Desktop.
You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries. Init
/**
* Calculates the maximum running time for `n` computers
* given a set of batteries with different capacities.
*
* @param {number} n - Number of computers
* @param {number[]} batteries - Array of battery capacities
* @return {number} - Maximum possible running time
*/
var maxRunTime = function(n, batteries) {
// Step 1: Compute the total available power across all batteries
let totalPower = 0;
for (let power of batteries) {
totalPower += power;
}
// Step 2: Define binary search boundaries
// Minimum possible time is 1
// Maximum possible time is average power per computer (upper bound)
let left = 1;
let right = Math.floor(totalPower / n);
// Step 3: Binary search to find the maximum feasible running time
while (left < right) {
// Midpoint (biased upward to avoid infinite loop)
let mid = right - Math.floor((right - left) / 2);
// Step 4: Calculate how much power can be used if each computer runs for `mid` time
let usablePower = 0;
for (let power of batteries) {
// Each battery can contribute at most `mid` units of power
usablePower += Math.min(power, mid);
}
// Step 5: Check feasibility
if (usablePower >= n * mid) {
// Enough power → try longer time
left = mid;
} else {
// Not enough power → reduce time
right = mid - 1;
}
}
// Step 6: Return the maximum feasible running time
return left;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment