将前 i 台洗衣机看成一组,记作 A,其余洗衣机看成另一组,记作 B。设 sum}[i]=\sum_{j=0}^i \textit{machines}[j]’,若 sum}[i] 为正则说明需要从 A 向 B 移入 sum}[i] 件衣服,为负则说明需要从 B 向 A 移入 -\textit{sum}[i] 件衣服。
我们分两种情况来考虑操作步数:
A 与 B 两组之间的衣服,最多需要 \max_{i=0}^{n-1}|\textit{sum}[i]| 次衣服移动;
classSolution: deffindMinMoves(self, machines: List[int]) -> int: tot = sum(machines) n = len(machines) if tot % n: return -1 avg = tot // n ans, s = 0, 0 for num in machines: num -= avg s += num ans = max(ans, abs(s), num) return ans
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: intfindMinMoves(vector<int> &machines){ int tot = accumulate(machines.begin(), machines.end(), 0); int n = machines.size(); if (tot % n) { return-1; } int avg = tot / n; int ans = 0, sum = 0; for (int num: machines) { num -= avg; sum += num; ans = max(ans, max(abs(sum), num)); } return ans; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { publicintfindMinMoves(int[] machines) { inttot= Arrays.stream(machines).sum(); intn= machines.length; if (tot % n != 0) { return -1; } intavg= tot / n; intans=0, sum = 0; for (int num : machines) { num -= avg; sum += num; ans = Math.max(ans, Math.max(Math.abs(sum), num)); } return ans; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
publicclassSolution { publicintFindMinMoves(int[] machines) { int tot = machines.Sum(); int n = machines.Length; if (tot % n != 0) { return-1; } int avg = tot / n; int ans = 0, sum = 0; foreach (int num in machines) { int tmp = num - avg; sum += tmp; ans = Math.Max(ans, Math.Max(Math.Abs(sum), tmp)); } return ans; } }
funcfindMinMoves(machines []int) (ans int) { tot := 0 for _, v := range machines { tot += v } n := len(machines) if tot%n > 0 { return-1 } avg := tot / n sum := 0 for _, num := range machines { num -= avg sum += num ans = max(ans, max(abs(sum), num)) } return }
funcabs(x int)int { if x < 0 { return -x } return x }
funcmax(a, b int)int { if b > a { return b } return a }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var findMinMoves = function(machines) { const tot = eval(machines.join('+')); const n = machines.length; if (tot % n !== 0) { return -1; } let avg = Math.floor(tot / n); let ans = 0, sum = 0; for (let num of machines) { num -= avg; sum += num; ans = Math.max(ans, Math.max(Math.abs(sum), num)); } return ans; };