Minimum Moves to Equal Array Elements II
Medium · Math & Geometry · Explanation and code example
Move All Values to a Median
How it works
For absolute-distance cost, moving the target within the middle pair changes left and right costs equally; outside the median range, more values pull the target back toward the middle. Choose a median and sum distances. Python sorts to find it; C++ selects it with nth_element.
Steps
- Find a median value.
- Compute the absolute difference from each value to the median.
- Return the sum.
Complexity
- Time: Python O(n log n); C++ O(n) average with nth_element.
- Space: Python O(n) for median sorting; C++ selection is in place.
Things to watch for
- For even length, any value between the two middle values is optimal.
- C++ selection rearranges the input.
- Use absolute differences, rather than signed sums.
Python code example
import statistics
class Solution:
def minMoves2(self, nums: list[int]) -> int:
median = int(statistics.median(nums))
return sum(abs(num - median) for num in nums)
C++ code example
class Solution {
public:
int minMoves2(vector<int>& nums) {
const int n = nums.size();
nth_element(nums.begin(), nums.begin() + n / 2, nums.end());
const int median = nums[n / 2];
return accumulate(nums.begin(), nums.end(), 0, [&](int acc, int num) {
return acc + abs(num - median);
});
}
};
Source and license
Explanation by LC Tracker. Code adapted from walkccc / Peng-Yu Chen · MIT license. Node types are supplied by LeetCode where needed.