Problem Description
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 by 1.
Key Insights
- The optimal target value to minimize total moves is the median of the array.
- Sorting the array helps in finding the median easily.
- The sum of absolute differences between each element and the median gives the minimum moves.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting
Space Complexity: O(n) (or O(1) if sorting is done in-place)
Solution
We first sort the array to locate the median. The median minimizes the sum of absolute differences from all elements, which means aligning all elements to the median will yield the fewest moves. After determining the median, we iterate through the array, summing the absolute differences between each element and the median. This summation gives the minimum moves necessary. Note that when the array has an even number of elements, any number between the two central elements serves as an optimal pivot.