Maximum Running Time of N Computers — LeetCode 2141 Python Solution
- Problem
- #2141
- Pattern
- Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes.
Example
- Input
- n = 2, batteries = [3,3,3]
- Output
- 4
- Explanation
- Initially, insert battery 0 into the first computer and battery 1 into the second computer.
Python solution
class Solution:
def maxRunTime(self, n: int, batteries: List[int]) -> int:
l, r = 0, sum(batteries)
while l < r:
mid = (l + r + 1) >> 1
if sum(min(x, mid) for x in batteries) >= n * mid:
l = mid
else:
r = mid - 1
return lComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log M), where M is the total power of all batteries |
| Space | O(1) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 2141. Maximum Running Time of N Computers is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2141. Maximum Running Time of N Computers?
- LeetCode 2141. Maximum Running Time of N Computers is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2141. Maximum Running Time of N Computers?
- The Python solution on this page runs in O(n \times \log M), where M is the total power of all batteries.
- What is the space complexity of LeetCode 2141. Maximum Running Time of N Computers?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2141. Maximum Running Time of N Computers cover?
- LeetCode 2141. Maximum Running Time of N Computers is tagged Greedy, Array, Binary Search and Sorting on LeetCode.