题目描述
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 representing the number of dresses in each washing machine from left to right on the line, you should find 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.
样例
Example1
Input: [1,0,5]
Output: 3
Explanation:
1st move: 1 0 <-- 5 => 1 1 4
2nd move: 1 <-- 1 <-- 4 => 2 1 3
3rd move: 2 1 <-- 3 => 2 2 2
Example2
Input: [0,3,0]
Output: 2
Explanation:
1st move: 0 <-- 3 0 => 1 2 0
2nd move: 1 2 --> 0 => 1 1 1
Example3
Input: [0,2,0]
Output: -1
Explanation:
It's impossible to make all the three washing machines have the same number of dresses.
算法
(枚举) O(n)
这题拿到没思路,不会做,看了 解答 ,真的是奇怪的知识又增加了......
参考文献
https://leetcode-cn.com/problems/super-washing-machines/solution/chao-ji-xi-yi-ji-by-leetcode/
Java 代码
class Solution {
public int findMinMoves(int[] machines) {
if (machines == null || machines.length == 0) {
return 0;
}
int n = machines.length, dressTotal = 0;
for (int i = 0; i < n; i++) {
dressTotal += machines[i];
}
if (dressTotal % n != 0) {
return -1;
}
// 为了方便计算,我们可以将所有的 N 个数分别减去 D / N,这样若第 i 台洗衣机对应的数为正数,说明它需要拿出衣服分给别的洗衣机;若第 i 台洗衣机对应的数为负数,说明它需要从别的洗衣机得到衣服。
int dressPerMachine = dressTotal / n;
for (int i = 0; i < n; i++) {
machines[i] -= dressPerMachine;
}
// 前缀和
int currSum = 0;
// 前缀和的绝对值的最大值
int maxSum = 0;
int res = 0, tmpRes = 0;
for (int m : machines) {
currSum += m;
maxSum = Math.max(maxSum, Math.abs(currSum));
tmpRes = Math.max(maxSum, m);
res = Math.max(res, tmpRes);
}
return res;
}
}