问题描述:
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].
问题分析:这是状态转移问题,每个洗衣机在同一时间只能向相邻洗衣机传递一件衣服,则合法的转移操作是在从左向右的+1、-1变化必须成对出现,例如:-1,0,+1,+1,0,0,0,-1,而这种-1,-1,0,0,+1,-1,0,+1,+1,+1是不合法的转移操作。而对于k个所有合法操作进行累加和,必然是需要转移的每个洗衣机与最终平衡洗衣机衣服数目的差值。对于合法操作的特点:从左向右进行累加,最大值必然是1,所以对于所有k个合法操作累加之后的合法操作同样进行从左向右累加,最大值必然是k,即转移操作的次数。由于每个合法操作的最大值出现的位置不同,从左向右累加和必须和当前洗衣机本身需要转移的衣服数目进行比较。
public int findMinMoves(int[] machines) {
int n=machines.length;
if(n<0)
return -1;
int sum=0;
for(int i=0;i<n;i++)
sum+=machines[i];
if(sum%n!=0)
return -1;
int avg=sum/n;
int leftnum=0;
int minmove=0;
for(int i=0;i<n;i++){
int cu=machines[i]-avg;
leftnum+=cu;
minmove=Math.max(minmove,Math.max(Math.abs(leftnum),cu));
}
return minmove;
}
参考链接:
http://blog.csdn.net/ljytfsto/article/details/60757973
http://blog.csdn.net/tstsugeg/article/details/62427718