#517
Hard Algorithms Super washing machines
Array Greedy
43.9% acceptance
Feb 19, 2026
823
222
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 machines representing the number of dresses in each washing machine from left to right on the line, return 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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn find_min_moves(machines: Vec<i32>) -> i32 {
let n = machines.len() as i32;
let total: i32 = machines.iter().sum();
if total % n != 0 { return -1; }
let avg = total / n;
let mut result = 0i32;
let mut cum = 0i32;
for &m in &machines {
cum += m - avg;
result = result.max(cum.abs()).max(m - avg);
}
result
}
}