Created
December 1, 2025 18:46
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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