Maximum Running Time of N Computers — LeetCode 2141 Python Solution

HardGreedyArrayBinary SearchSorting
Problem
#2141
Reading time
2 min

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

Python
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 l

Complexity

MeasureComplexity
TimeO(n \times \log M), where M is the total power of all batteries
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview