#2141
Maximum Running Time of N Computers
HardArrayBinary SearchGreedySortingBinary SearchGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log(sum(batteries))) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log(sum(batteries)))Space O(1)
The optimal solution uses binary search to efficiently find the maximum running time. Instead of checking every possible time, we can narrow down our search space based on whether a certain time is feasible or not.
⚙️
Algorithm
4 steps- 1Step 1: Set low = 0 and high = sum of batteries.
- 2Step 2: While low < high, calculate mid = (low + high + 1) // 2.
- 3Step 3: Check if it's possible to run all n computers for 'mid' minutes. If yes, set low = mid; otherwise, set high = mid - 1.
- 4Step 4: Return low as the maximum running time.
solution.py16 lines
1# Full working Python code
2
3def canRunForTime(n, batteries, time):
4 totalPower = sum(min(battery, time) for battery in batteries)
5 return totalPower >= n * time
6
7
8def maxRunTime(n, batteries):
9 low, high = 0, sum(batteries)
10 while low < high:
11 mid = (low + high + 1) // 2
12 if canRunForTime(n, batteries, mid):
13 low = mid
14 else:
15 high = mid - 1
16 return lowℹ
Complexity note: The time complexity is O(n log(sum(batteries))) because we perform a binary search over the range of possible times, and for each mid value, we check if it's feasible by summing the batteries, which takes O(n).
- 1Binary search allows us to efficiently find the maximum running time.
- 2The feasibility check for a given time is crucial for narrowing down the search space.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.