题目
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.
答案
思考的方法
题目说每个move可以同时把很多个洗衣机的一件衣服往左或者往右移动
如果你直接去想怎么移动才能使得所有洗衣机包含同样数量的衣服,很难想出一个办法来
但是如果你假设题目所给出的移动方法可以使你用最少的步数达到平衡(每个洗衣机衣服数量相等),然后再去思考在最好的情况下,用多少步就能达到平衡,这样或许会更容易找到答案。
代码
class Solution {
public int findMinMoves(int[] machines) {
int sum = 0, balance = 0, moves = 0, target = 0, n = machines.length;
for(int x : machines) sum += x;
if(sum % n != 0) return -1;
target = sum / machines.length;
for(int i = 0; i < n; i++) {
int left = 0;
if(balance < 0) {
left = -balance;
moves = Math.max(moves, left);
}
balance += (machines[i] - target);
if(balance > 0)
moves = Math.max(moves, balance + left);
}
return moves;
}
}