Problem Description
Explanation:
To solve this problem, we need to find the minimum number of moves required to make all the washing machines have the same number of dresses. We can approach this by calculating the excess dresses that need to be moved from one machine to another at each step.
- First, calculate the total sum of dresses in all machines.
- Check if the total sum can be evenly distributed among all machines. If not, return -1 as it is not possible.
- Iterate through the machines and calculate the required dresses at each machine to reach the average number of dresses.
- At each step, calculate the maximum excess dresses that need to be moved to/from a machine.
- Keep track of the maximum moves required to balance the machines.
Time Complexity:
The time complexity of this approach is O(n) where n is the number of machines.
Space Complexity:
The space complexity is O(1) since we are using constant extra space.
:
Solutions
class Solution {
public int findMinMoves(int[] machines) {
int n = machines.length;
int total = 0;
for (int machine : machines) {
total += machine;
}
if (total % n != 0) {
return -1;
}
int avg = total / n;
int moves = 0;
int balance = 0;
for (int machine : machines) {
balance += machine - avg;
moves = Math.max(moves, Math.max(Math.abs(balance), machine - avg));
}
return moves;
}
}
Related LeetCode Problems
Loading editor...