Solution: Maximum Running Time of N Computers
Let’s solve the Maximum Running Time of N Computers problem using the Modified Binary Search Pattern.
We'll cover the following
Statement
You are given an integer, n
, representing the number of computers, and a 0-indexed integer array, batteries
, where batteries[i]
denotes the number of minutes the
Your goal is to run all n
computers simultaneously for the maximum possible number of minutes using the available batteries.
Initially, you may assign at most one battery to each computer. After that, at any moment, you may remove a battery from a computer and replace it with another battery—either an unused battery or one taken from another computer. This replacement process can be repeated any number of times and takes no time.
Each battery can power any computer multiple times, but only until it is completely drained. Batteries cannot be recharged.
Return the maximum number of minutes you can run all n
computers simultaneously.
Constraints:
1
n
batteries.length
1
batteries[i]
Solution
This solution aims to find the maximum number of minutes all n
computers can run simultaneously using a set of batteries. We use a modified binary search pattern on the possible runtime values to achieve this. The key observation is that if it’s possible to run all n
computers for x
minutes, it is also possible to run them for any time less than x
. This total_power // n
, where total_power
is the sum of all battery capacities. At each step, we check whether running all computers for mid
minutes is feasible by verifying that the sum of the available battery contributions (each battery contributing up to mid
minutes) is at least n * mid
. This feasibility check helps us efficiently narrow down the maximum achievable runtime.
Now, let’s look at the solution steps below:
Set
left = 0
andright = sum(batteries) // n
to define the minimum and maximum possible simultaneous runtime.While
left < right
:Calculate
mid = right - (right - left) // 2
(biases the midpoint toward the higher end to avoid infinite loops).Initialize
usable = 0
to store the sum of usable power.For each battery, add
min(b, mid)
tousable
.If
usable >= mid × n
, the target is feasible, so setleft = mid
to search for a longer time.Otherwise, set
right = mid - 1
to search in the lower half.
After the loop completes,
left
holds the maximum number of minutes that alln
computers can run simultaneously.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.