题目描述
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
(贪心) $O(n)$
- 参考 AcWing 1536. 均分纸牌 。
- 和均分纸牌不同,本题一次可以操作多个堆,但是每个堆只能移动一张纸牌,但是最终状态所需要的纸牌移动次数都是一样的。
C++ 代码
class Solution {
public:
int findMinMoves(vector<int>& machines) {
int sum = 0, n = machines.size();
for (int x : machines) sum += x;
if (sum % n) return -1;
int avg = sum / n, res = 0;
for (int i = 0, d = 0; i < n; ++i) {
// 当前堆到达最终状态需要的最少移动次数d
d += machines[i] - avg;
// 和当前堆直接变为最终状态所需的移动次数取最大值
res = max(res, max(abs(d), machines[i] - avg));
}
return res;
}
};