Maximum Running Time of N Computers - Problem

You have n computers and are given an integer array batteries where batteries[i] represents the number of minutes the i-th battery can power a computer.

Your goal is to run all n computers simultaneously for the maximum possible time using the available batteries.

Rules:

  • Initially, you can insert at most one battery into each computer
  • At any time, you can remove a battery and insert another battery (takes no time)
  • You can move batteries between computers freely
  • Batteries cannot be recharged

Return the maximum number of minutes you can run all n computers simultaneously.

Input & Output

Example 1 — Basic Case
$ Input: n = 2, batteries = [3,3,3,1]
Output: 5
💡 Note: We can run 2 computers for 5 minutes. Total power needed = 2×5 = 10. Available power = min(3,5)+min(3,5)+min(3,5)+min(1,5) = 3+3+3+1 = 10 ✓
Example 2 — Larger Batteries
$ Input: n = 2, batteries = [1,1,1,1]
Output: 2
💡 Note: We can run 2 computers for 2 minutes. Total power needed = 2×2 = 4. Available power = 1+1+1+1 = 4 ✓
Example 3 — Single Computer
$ Input: n = 1, batteries = [1,1,1,1]
Output: 4
💡 Note: Only 1 computer, so we can use all battery power: 1+1+1+1 = 4 minutes total

Constraints

  • 1 ≤ n ≤ 105
  • n ≤ batteries.length ≤ 105
  • 1 ≤ batteries[i] ≤ 109

Visualization

Tap to expand
Maximum Running Time of N Computers INPUT n = 2 computers PC 1 PC 2 batteries = [3, 3, 3, 1] 3 B0 3 B1 3 B2 1 B3 Total Power: 3+3+3+1 = 10 mins Goal: Run 2 PCs simultaneously as long as possible ALGORITHM STEPS 1 Binary Search Setup Search range: [1, total/n] lo=1, hi=10/2=5 2 Check mid = 3 Need: 2*3 = 6 mins total Have: min(3,3)+min(3,3)+ min(3,3)+min(1,3)=10 OK 3 Check mid = 5 Need: 2*5 = 10 mins total Have: min(3,5)+min(3,5)+ min(3,5)+min(1,5)=10 OK 4 Check mid = 6 Need: 2*6 = 12 mins total Have: 3+3+3+1=10 FAIL Not enough power! 1--2--3--4--[5]--6--7--8--9--10 Answer found at 5 Greedy: Distribute power evenly FINAL RESULT Output: 5 minutes Verification: Time 0-3 3-5 PC1 B0 B3 B2 PC2 B1 B2 B0:3 + B1:3 + B2:3 + B3:1 = 10 Per PC: 10/2 = 5 mins each Both run for 5 mins: OK VERIFIED OK Max time = 5 Time: O(n log(sum)) Space: O(1) Key Insight: Binary search on the answer! For time T to be achievable, we need sum(min(battery[i], T)) greater than or equal to n*T. Each battery contributes at most T minutes (no single PC needs more). The greedy insight is that if total usable power covers n*T, we can always distribute it optimally by swapping batteries. TutorialsPoint - Maximum Running Time of N Computers | Greedy Optimal Distribution
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
28.0K Views
Medium Frequency
~25 min Avg. Time
980 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen