Maximum Running Time of N Computers

With k batteries (any one can power any computer, swappable instantly), maximize minutes all n computers can run — binary search on answer.

Hard
Time O(k log totalPower) Space O(1)
LeetCode
4 min read
binary-search

Problem#

n computers, k batteries with capacities batteries[i]. At any second, any battery can power one computer (or be idle); swaps are free. Return the maximum number of minutes all n computers can run simultaneously.

Examples#

  • n = 2, batteries = [3,3,3]4
  • n = 2, batteries = [1,1,1,1]2

Hints#

Hint 1
For a candidate minute count t, each battery contributes min(t, capacity) to the pool. Feasible iff total ≥ n * t.

Approach#

Binary search on t. The feasibility predicate sums min(t, c) and compares to n * t.

Solution#

Maximum Running Time
class Solution {
public:
long long maxRunTime(int n, vector<int>& batteries) {
auto feasible = [&](long long t) {
long long total = 0;
for (int c : batteries) total += min((long long)c, t);
return total >= (long long)n * t;
};
long long lo = 1, hi = accumulate(batteries.begin(), batteries.end(), 0LL) / n;
while (lo < hi) {
long long mid = lo + (hi - lo + 1) / 2;
if (feasible(mid)) lo = mid;
else hi = mid - 1;
}
return lo;
}
};

Editorial#

The non-obvious capacity-clipping min(t, c) is the elegance: a battery with c > t contributes only t (it can’t help past minute t); a battery with c <= t contributes c. The total contribution must cover n * t minute-units of demand.

Complexity#

  • Time: O(k log totalPower).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.