Problem Description
Given n washing machines on a line where each machine holds some number of dresses, determine the minimum number of moves required to redistribute the dresses so that every machine has the same number. In one move, you can choose any set of machines and move one dress from each chosen machine to an adjacent machine. If it is impossible to achieve equal dresses across all machines, return -1.
Key Insights
- The total number of dresses must be divisible by the number of machines; otherwise, it's impossible.
- The target number of dresses per machine is the average (total dresses / n).
- At each machine, calculate the difference (current - target). This difference tells if the machine needs to give away dresses (if positive) or receive dresses (if negative).
- Use a running total (cumulative balance) to keep track of the net dresses that should move across machines. The maximum absolute cumulative balance indicates the moves caused by “passing” dresses along the line.
- The maximum number of moves required at any machine is the maximum of:
- The absolute value of the cumulative sum (tracking dresses passing by).
- The number of dresses that need to be dumped from one machine (if current count exceeds target).
Space and Time Complexity
Time Complexity: O(n) – We pass over the array of machines once. Space Complexity: O(1) – Only a constant amount of extra space is used.
Solution
The solution works by first ensuring that the total number of dresses can be evenly distributed across all machines. Next, for each machine, we calculate the difference between its current number of dresses and the target number. As we iterate through the machines, we maintain a running total (cumulative balance) of these differences. The key insight is that at any machine, the number of moves required will be the maximum of the absolute cumulative balance (which represents dresses being transferred across machines) and the local surplus (if any). The answer is the maximum of these values over all machines.