LeetCode Solutions

517. Super Washing Machines

Time: $O(n)$

Space: $O(1)$

			

class Solution {
 public:
  int findMinMoves(vector<int>& machines) {
    const int dresses = accumulate(begin(machines), end(machines), 0);
    if (dresses % machines.size() != 0)
      return -1;

    int ans = 0;
    int inout = 0;
    const int average = dresses / machines.size();

    for (const int dress : machines) {
      inout += dress - average;
      ans = max({ans, abs(inout), dress - average});
    }

    return ans;
  }
};
			

class Solution {
  public int findMinMoves(int[] machines) {
    int dresses = Arrays.stream(machines).sum();
    if (dresses % machines.length != 0)
      return -1;

    int ans = 0;
    int inout = 0;
    final int average = dresses / machines.length;

    for (final int dress : machines) {
      inout += dress - average;
      ans = Math.max(ans, Math.max(Math.abs(inout), dress - average));
    }

    return ans;
  }
}
			

class Solution:
  def findMinMoves(self, machines: List[int]) -> int:
    dresses = sum(machines)

    if dresses % len(machines) != 0:
      return -1

    ans = 0
    average = dresses // len(machines)
    inout = 0

    for dress in machines:
      inout += dress - average
      ans = max(ans, abs(inout), dress - average)

    return ans