问题描述:
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.
Note:
- The range of n is [1, 10000].
- The range of dresses number in a super washing machine is [0, 1e5].
问题分析:
对于任何一个给定的机器wi,假设它左边缺少或者多出L件衣服,即 L = avg *i - w0 -w1 -...w(i-1)
假设它右边缺少或者多出R件衣服,即R = avg*(n - i - 1) - w(i +1) - w(i+2)-....w(n)
那么有如下几种可能:
1.L<=0 && R <= 0 即wi非常多,既需要向左边移动,又需要往右边移动,因为一个洗衣机一次仅能移动一件衣服,所以此时 step = max(step, abs(L) + abs(R))
2.L<=0 && R > 0 即wi需要往左边移动衣服,同时右边需要往wi移动衣服,因为wi和w(i+1)可以同时移动衣服,所以step = max(step, abs(L), abs(R))
3.L > 0 && R <= 0 即wi需要从左边移动衣服,同时需要往右边移动衣服,w(i -1)和wi可以同时移动衣服,所以step = max(step, abs(L), abs(R))
4.L > 0 && R > 0 即wi非常少,需要同时从左右移动衣服,因为左右可以同时移动,所以step=max(step, abs(L), abs(R))
实现代码如下:
class Solution {
public:
int findMinMoves(vector<int>& machines)
{
int sum = 0;
for (int i = 0; i <machines.size(); ++i)
{
sum += machines[i];
}
if (sum % machines.size() != 0) return -1;
int avg = sum/machines.size();
int steps = 0;
int l = 0;
int r = avg - machines[0];
for (int i = 0 ; i < machines.size(); ++i)
{
if (l <= 0 && r <= 0) steps = std::max(steps, -l - r);
else steps = std::max(steps, std::max(std::abs(l), std::abs(r)));
l = l + machines[i] - avg;
r = r - machines[i + 1] + avg;
}
return steps;
}
};