leetcode: super washing machines

本文介绍了一种算法,用于计算使一系列超级洗衣机中的衣物数量达到平衡所需的最小移动次数。通过分析洗衣机间衣物分布情况,该算法能够高效地解决这一问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述:

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].

问题分析:

对于任何一个给定的机器wi,假设它左边缺少或者多出L件衣服,即 L = avg *i - w0 -w1 -...w(i-1)

假设它右边缺少或者多出R件衣服,即R = avg*(n - i - 1) - w(i +1) - w(i+2)-....w(n)

那么有如下几种可能:

1.L<=0 && R <= 0   即wi非常多,既需要向左边移动,又需要往右边移动,因为一个洗衣机一次仅能移动一件衣服,所以此时 step = max(step, abs(L) + abs(R))

2.L<=0 && R > 0  即wi需要往左边移动衣服,同时右边需要往wi移动衣服,因为wi和w(i+1)可以同时移动衣服,所以step = max(step, abs(L), abs(R))

3.L > 0 && R <= 0 即wi需要从左边移动衣服,同时需要往右边移动衣服,w(i -1)和wi可以同时移动衣服,所以step = max(step, abs(L), abs(R))

4.L > 0 && R > 0 即wi非常少,需要同时从左右移动衣服,因为左右可以同时移动,所以step=max(step, abs(L), abs(R))

实现代码如下:

class Solution {
public:
    int findMinMoves(vector<int>& machines) 
    {
        int sum = 0;
        for (int i = 0; i <machines.size(); ++i)
        {
            sum += machines[i];
        }
        
        if (sum % machines.size() != 0) return -1;
        int avg = sum/machines.size();

        int steps = 0;
        int l = 0;
        int r =  avg - machines[0];
        for (int i = 0 ; i < machines.size(); ++i)
        {
            if (l <= 0 && r <= 0) steps = std::max(steps, -l - r);
            else steps = std::max(steps, std::max(std::abs(l), std::abs(r)));

            l = l + machines[i] - avg;
            r = r - machines[i + 1] + avg;
        }
        return steps;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值