Skip to content

2141. Maximum Running Time of N Computers 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  long long maxRunTime(int n, vector<int>& batteries) {
    long sum = accumulate(batteries.begin(), batteries.end(), 0L);

    ranges::sort(batteries);

    // The maximum battery is greater than the average, so it can last forever.
    // Reduce the problem from size n to size n - 1.
    while (batteries.back() > sum / n) {
      sum -= batteries.back(), batteries.pop_back();
      --n;
    }

    // If the maximum battery <= average running time, it won't be waste, and so
    // do smaller batteries.
    return sum / n;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public long maxRunTime(int n, int[] batteries) {
    long sum = Arrays.stream(batteries).asLongStream().sum();

    Arrays.sort(batteries);

    // The maximum battery is greater than the average, so it can last forever.
    // Reduce the problem from size n to size n - 1.
    int i = batteries.length - 1;
    while (batteries[i] > sum / n) {
      sum -= batteries[i--];
      --n;
    }

    // If the maximum battery <= average running time, it won't be waste, and so
    // do smaller batteries.
    return sum / n;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def maxRunTime(self, n: int, batteries: list[int]) -> int:
    summ = sum(batteries)

    batteries.sort()

    # The maximum battery is greater than the average, so it can last forever.
    # Reduce the problem from size n to size n - 1.
    while batteries[-1] > summ // n:
      summ -= batteries.pop()
      n -= 1

    # If the maximum battery <= average running time, it won't be waste, and so
    # do smaller batteries.
    return summ // n