当前位置:网站首页>[Title brushing] Super washing machine

[Title brushing] Super washing machine

2022-06-12 13:10:00 m0_ sixty million six hundred and thirty-one thousand three hun

One 、 subject

OJ link

Suppose there is n The super washing machine is on the same row . At the beginning , There may be a certain amount of clothes in each washing machine , Or it could be empty .
In each step , You can choose whatever m (1 <= m <= n) Washing machine , At the same time, send a piece of clothes from each washing machine to an adjacent washing machine .
Given an array of integers machines Represents the number of clothes in each washing machine from left to right , Please give the number of clothes left in all washing machines equal Minimum number of operation steps . If you can't make the number of clothes in each washing machine equal , Then return to -1 .

 Insert picture description here

Two 、 Answer key

2.1 Ideas

Calculate the answer at a single point and then decide the final result

 Insert picture description here

2.2 Source code

 public static  int findMinMoves(int[] machines) {
    
           if(machines==null||machines.length==0){
    
               return 0;
           }
           int size=machines.length;
           int sum=0;
        for (int i = 0; i < size; i++) {
    
            sum+=machines[i];
        }
        if(sum%size!=0){
    
            return -1;
        }
        int avg=sum/size;
        int leftSum=0;
        int ans=0;
        for (int i = 0; i < machines.length; i++) {
    
            int leftRest=leftSum-i*avg;
            int rightRest=(sum-leftSum-machines[i])-(size-i-1)*avg;
            if(leftRest<0&&rightRest<0){
    
                ans=Math.max(ans,Math.abs(leftRest)+Math.abs(rightRest));
            }else {
    
                ans=Math.max(ans,Math.max(Math.abs(leftRest),Math.abs(rightRest)));

            }
            leftSum+=machines[i];
        }
        return ans;
    }
原网站

版权声明
本文为[m0_ sixty million six hundred and thirty-one thousand three hun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121302383246.html