Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created December 1, 2025 22:41
Show Gist options
  • Select an option

  • Save Ifihan/01e383b0d8fc3b0f4e6aadeeb8251d0e to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/01e383b0d8fc3b0f4e6aadeeb8251d0e to your computer and use it in GitHub Desktop.
Maximum Running Time of N Computers

Question

Approach

I binary-search the maximum running time T. For a candidate T I check if the total available minutes (summing min(b, T) for every battery b) is at least n * T — because each computer needs T minutes and a single battery can contribute at most T minutes toward a given computer. If the check passes, T is feasible and I try larger values; otherwise I try smaller ones.

Implementation

class Solution:
    def maxRunTime(self, n: int, batteries: List[int]) -> int:
        total = sum(batteries)

        lo, hi = 0, total // n

        def feasible(T: int) -> bool:
            need = n * T
            s = 0
            for b in batteries:
                s += b if b <= T else T
                if s >= need:
                    return True
            return False

        while lo < hi:
            mid = (lo + hi + 1) // 2
            if feasible(mid):
                lo = mid
            else:
                hi = mid - 1

        return lo

Complexities

  • Time: O(m * log S)
  • Space: O(1)
image
@Elvmeen
Copy link

Elvmeen commented Dec 1, 2025

The algorithm is "ONLY" optimal in theory, but performance could degrade/become slow with very large inputs because it keeps checking all the batteries over and over in each step. 😉

@Ifihan
Copy link
Author

Ifihan commented Dec 21, 2025

Oh. That's because that was the solution I could come up with. Not meant to be perfect but can be iterated upon

@Elvmeen
Copy link

Elvmeen commented Dec 21, 2025

Btw, there are better ways. Have a good night

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment