Problem Description
Given n computers and an array of batteries where each battery’s value indicates the number of minutes it can run a computer, determine the maximum number of minutes you can run all n computers simultaneously. You may initially place at most one battery in each computer and can later swap batteries between computers arbitrarily fast. Batteries cannot be recharged.
Key Insights
- The total available energy is the sum of all battery capacities.
- The maximum running time T is bounded by the total energy divided by n.
- For each battery, only up to T minutes of its energy are useful.
- Use binary search on T and for each candidate, check if the sum of min(battery, T) over all batteries is at least n * T.
Space and Time Complexity
Time Complexity: O(m * log(s)) where m is the number of batteries and s is the sum of battery capacities divided by n. Space Complexity: O(1) additional space (ignoring input storage).
Solution
We use binary search over the possible running times T. The minimum T is 0, and the maximum is the sum of all batteries divided by n. For each candidate T, we check if it is feasible to run n computers by accumulating min(battery, T) from each battery — since a battery can contribute at most T minutes toward the required runtime if it has extra energy. If the total accumulated energy is at least T * n, then running the computers for T minutes is possible. Accordingly, we adjust the binary search bounds until we identify the maximum feasible T. This approach leverages binary search and a greedy aggregate over battery capacities to meet the running time requirement.