[LeetCode] Super Washing Machines

517. Super Washing Machines

You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty.

For each move, you could choose any m (1 <= m <= n) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time.

Given an integer array machines representing the number of dresses in each washing machine from left to right on the line, return the minimum number of moves to make all the washing machines have the same number of dresses. If it is not possible to do it, return -1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int findMinMoves(vector<int>& A) {
long long sum = accumulate(begin(A), end(A), 0ll), n = A.size();
if(sum % n) return -1;
int res = 0, best = sum / n, pass = 0;

for(auto& a : A) {
pass = a + pass - best;
res = max({res, abs(pass), a - best});
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/21/PS/LeetCode/super-washing-machines/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.