题目描述
你有n台超级洗衣机。最初,每台洗衣机都有一些衣服或是空的。
对于每一次移动,您可以选择任意m台(1≤m≤n)洗衣机,并将每台洗衣机的一件衣服同时传递给相邻的洗衣机
给定一个整数数组表示每个洗衣机中从左到右的衣服数量,您应该找到最小移动次数,使得所有洗衣机中具有相同数量的衣服。如果无法执行此操作,请返回-1。
样例1
输入: [1,0,5]
输出: 3
解释:
第一次移动: 1 0 <-- 5 => 1 1 4
第二次移动: 1 <-- 1 <-- 4 => 2 1 3
第三次移动: 2 1 <-- 3 => 2 2 2
样例2
输入: [0,3,0]
输出: 2
解释:
第一次移动: 0 <-- 3 0 => 1 2 0
第二次移动: 1 2 --> 0 => 1 1 1
样例3
输入: [0,2,0]
输出: -1
解释:
不可能让所有洗衣机都有相同数量的衣服.
题解
考点:
- 思维
题解:
例如[0,0,11,5],需要得到[4,4,4,4],构造差值数组[-4,-4,7,1]。
- [-4,-4,7,1]->[0,-8,7,1]->[0,0,0,0]
移动的最大次数就是差值数组中出现的绝对值最大的数字,因为在差值最大处完成转移的过程中,就可以同时使得其他处为0。
想要了解更多大厂面试题解,可以来上九章算法班,提供免费试听。
public class Solution {
/**
* @param machines: an integer array 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
*/
public int findMinMoves(int[] machines) {
// Write your code here
int total = 0;
for (int i: machines) {
total += i;
}
if (total % machines.length != 0) { //判断不能完成
return -1;
}
int avg = total/machines.length, cnt = 0, max = 0;
for (int load: machines) {
cnt += load-avg; //load-avg is "gain/lose"
max = Math.max(Math.max(max, Math.abs(cnt)), load-avg); //找出此过程中差值绝对值的最大值
}
return max;
}
}