题目
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.
解法
给定一个长度为n的整数数组,每次选择m个数(1 ≤ m ≤ n)进行移动:将这m个数减1,同时令其相邻的一个数加1(这m个数同时可以是被加元素)
求最少需要多少次移动,使得数组中的所有数都相等。如果不能,则返回-1。
要使得每台洗衣机具有一样的衣服数,即数组中的所有数最后都相等,需要数组中数的总和是数组长度的整数倍,若sum % len != 0,则无法满足条件,返回-1。
对于满足条件的数组,计算需要移动的最小次数,因为每次只能改变1,所以machines[i] - ave为machines[i]达到平衡需要移动的步数,从左向右计算,用move表示达到平衡需要移动的累加次数。 max(machines[i] - ave,和abs(move)为需要移动的最小步数。
class Solution {
public:
int findMinMoves(vector<int>& machines) {
int sum = 0, len = machines.size();
for (auto m : machines)
sum += m;
if (sum % len != 0) return -1;
int ave = sum / len;
int res = 0, move = 0;
for (int i = 0; i < len; i++) {
move += machines[i] - ave;
res = max(res, max(machines[i] - ave, abs(move)));
}
return res;
}
};