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: Distribute Battery Power OptimallyComputers (n=2):PC 1PC 2Batteries:3331Goal: Find max T where available_power ≥ n × TFor T=5: available = min(3,5)+min(3,5)+min(3,5)+min(1,5) = 10Need n×T = 2×5 = 10 power ✓Maximum: 5 minutes
Understanding the Visualization
1
Input
n=2 computers, batteries=[3,3,3,1]
2
Process
Find max time T where total_power ≥ n×T
3
Output
Maximum runtime = 5 minutes
Key Takeaway
🎯 Key Insight: Use binary search on runtime with greedy power distribution check
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