DDSA Solutions

2141. Maximum Running Time of N Computers

Problem Overview

Maximum Running Time of N Computers (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Binary Search pattern in coding interviews. Binary search on run time; validate by checking total battery sum >= n * mid.

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

Approach

Binary search on run time; validate by checking total battery sum >= n * mid.

Related patterns: Array, Binary Search, Greedy

2141.cs
C#
// Approach: Binary search on run time; validate by checking total battery sum >= n * mid.
// Time: O(b log(sum/n)) Space: O(1)

public class Solution
{
    public long MaxRunTime(int n, int[] batteries)
    {
        long left = 0;
        long right = 0;
        foreach (int battery in batteries)
            right += battery;

        while (left < right)
        {
            long mid = (left + right + 1) >> 1;

            long totalUsableCapacity = 0;
            foreach (int battery in batteries)
                totalUsableCapacity += Math.Min(mid, battery);

            if (totalUsableCapacity >= n * mid)
                left = mid;
            else
                right = mid - 1;
        }

        return left;
    }
}
Was this solution helpful?

Related Problems