Minimum Moves to Equal Array Elements II

medium array math sorting

Problem

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.

Inputnums = [1, 2, 3]
Output2
Bring 1 → 2 (+1) and 3 → 2 (−1); total moves = 2.

def min_moves2(nums):
    nums.sort()
    m = nums[len(nums) // 2]
    return sum(abs(x - m) for x in nums)
function minMoves2(nums) {
  nums.sort((a, b) => a - b);
  const m = nums[Math.floor(nums.length / 2)];
  return nums.reduce((s, x) => s + Math.abs(x - m), 0);
}
class Solution {
    public int minMoves2(int[] nums) {
        Arrays.sort(nums);
        int m = nums[nums.length / 2];
        int total = 0;
        for (int x : nums) total += Math.abs(x - m);
        return total;
    }
}
int minMoves2(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    int m = nums[nums.size() / 2];
    int total = 0;
    for (int x : nums) total += abs(x - m);
    return total;
}
Time: O(n log n) with sort, O(n) with quickselect Space: O(1)