Leetcode 517. 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. 

Note:

  1. The range of n is [1, 10000].
  2. 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值