Super Washing Machines

题目
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;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,110评论 0 23
  • 彼时 此时 現在人的愛情 平淡無奇
    人格不稳定少女阅读 202评论 0 0
  • 姓名:周黎明 公司:宁波贞观电器有限公司 组别:宁波盛和塾第 224期努力一组 日精打卡时间:精打卡第192天 ...
    A周黎明阅读 165评论 0 0
  • 营销有四个资源,由低向高依次是关系、产品、风险、服务,最低端的资源是关系,其次是产品和风险,最后是服务。 作者:自...
    吴少杰1988阅读 263评论 0 0
  • 很久没更新,今天看到有人评论说很希望能更新下去,最近工作事物繁多,主要又在写C#+Webapi这一块。近来用nod...
    Tony_HQ阅读 770评论 2 0