517. Super Washing Machines

来源:互联网 发布:c语言经典实例 编辑:程序博客网 时间:2024/05/16 23:37

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: 3Explanation: 1st move:    1     0 <-- 5    =>    1     1     42nd move:    1 <-- 1 <-- 4    =>    2     1     3    3rd move:    2     1 <-- 3    =>    2     2     2   

Example2

Input: [0,3,0]Output: 2Explanation: 1st move:    0 <-- 3     0    =>    1     2     0    2nd move:    1     2 --> 0    =>    1     1     1     

Example3

Input: [0,2,0]Output: -1Explanation: 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].

思路: * 因为一次只能从一个节点往左或者往右
 * 每个节点只会往一个方向前进(要么全部向左,要么全部向右)
 * 计算“流量”最大的那个点(某个节点的流量包括其他节点从该节点通过的流量)

我记得之前调试这个调了很久,但是今天思路却很清晰,看来也不能一直死纠结一道题,过一段时间也许就豁然开朗,这也许是为什么刷题需要时间的缘故吧
public class Solution {    public int findMinMoves(int[] machines) {        int sum = 0;        for(int i : machines)sum+=i;        if(sum % machines.length != 0)return -1;                int ave = sum / machines.length;        int[] diff = new int[machines.length];        // 注意这里是machines[i] - ave,与maxFlux = Math.max(i, maxFlux);中i没有abs相对应        for(int i=0; i<machines.length; i++) diff[i] = machines[i] - ave;                // 通过的流量        int maxFlux = 0;        int[] totalFlux = new int[machines.length];        totalFlux[0] = diff[0];for(int i=1; i<totalFlux .length; i++) {        totalFlux[i] = totalFlux[i-1] + diff[i];        maxFlux = Math.max(maxFlux, Math.abs(totalFlux[i]));        }// 一个时间只能往一个方向走,所以还要比一遍每个节点需要往外送出去的量for(int i : diff)maxFlux = Math.max(i, maxFlux);                return maxFlux;    }}



原创粉丝点击