#462
Medium Algorithms Minimum moves to equal array elements ii
Array Math Sorting
61.5% acceptance
Jan 13, 2026
3516
132
Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.
In one move, you can increment or decrement an element of the array by 1.
Test cases are designed so that the answer will fit in a 32-bit integer.
Solution
Rust
Time O(n log n)
Space O(1)
impl Solution {
pub fn min_moves2(mut nums: Vec<i32>) -> i32 {
nums.sort();
let median = nums[nums.len() / 2];
nums.iter().map(|&n| (n - median).abs()).sum()
}
}