Sponsored
Sponsored
The greedy approach involves determining the imbalance of dresses between adjacent machines and making moves to balance it. We find the maximum number of dresses that need to be moved either into or out of any machine to balance the system.
If it's impossible to balance the dresses equally among all machines (i.e., the total number of dresses is not divisible by the number of machines), the solution is -1.
Time Complexity: O(n), where n is the number of machines.
Space Complexity: O(1), since we use a constant amount of extra space.
1function findMinMoves(machines) {
2 let totalDresses = machines.reduce((a, b) => a + b, 0);
3 const n = machines.length;
4 if (totalDresses % n !== 0) return -1;
5 const target = totalDresses / n;
6 let maxMoves = 0, balance = 0;
7 for (const dresses of machines) {
8 let diff = dresses - target;
9 balance += diff;
10 maxMoves = Math.max(maxMoves, Math.abs(balance), diff);
11 }
12 return maxMoves;
13}
14
15console.log(findMinMoves([1, 0, 5])); // Output: 3
This JavaScript implementation uses array operations to determine the target load and then calculates the required moves by balancing each machine sequentially against this target.