Skip to content

517. Super Washing Machines

  • Time: $O(n)$
  • 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:
  int findMinMoves(vector<int>& machines) {
    const int dresses = accumulate(machines.begin(), machines.end(), 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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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