Skip to content

2141. Maximum Running Time of N Computers

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. You are interested in running all n computers simultaneously using the given batteries.

Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time.

Note that the batteries cannot be recharged.

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

Solve

First implementation - Simulation

class Solution:
    def maxRunTime(self, n: int, batteries: List[int]) -> int:
        if n == len(batteries):
            return min(batteries)

        time = 0

        while len(batteries) >= n:
            batteries.sort(reverse = True)
            runOut = []
            for i in range(n):
                batteries[i] = batteries[i] - 1
                if batteries[i] == 0:
                    runOut.append(i)
            for i in runOut[::-1]:
                batteries.pop(i)
            time += 1

        return time

Last update : October 13, 2023
Created : August 16, 2023