# 462. Minimum Moves to Equal Array Elements II

Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.

You may assume the array’s length is at most 10,000.

Example:

``````Input:
[1,2,3]

Output:
2

Explanation:
Only two moves are needed (remember each move increments or decrements one element):

[1,2,3]  =>  [2,2,3]  =>  [2,2,2]
``````

``````class Solution {
public:
int minMoves2(vector<int>& nums) {
int res = 0, i = 0, j = (int)nums.size() - 1;
sort(nums.begin(), nums.end());
while (i < j) {
res += nums[j--] - nums[i++];
}
return res;
}
};
``````

``````class Solution {
public:
int minMoves2(vector<int>& nums) {
sort(nums.begin(), nums.end());
int res = 0, mid = nums[nums.size() / 2];
for (int num : nums) {
res += abs(num - mid);
}
return res;
}
};
``````

``````class Solution {
public:
int minMoves2(vector<int>& nums) {
int res = 0, n = nums.size(), mid = n / 2;
nth_element(nums.begin(), nums.begin() + mid, nums.end());
for (int i = 0; i < n; ++i) {
res += abs(nums[i] - nums[mid]);
}
return res;
}
};
``````

Y = k - nums[0] + k - nums[1] + … + k - nums[i - 1] + nums[i] - k + nums[i + 1] - k + … + nums[n - 1] - k

= i * k - (nums[0] + nums[1] + … + nums[i - 1]) + (nums[i] + nums[i + 1] + … + nums[n - 1]) - (n - i) * k

= 2 * i * k - n * k + sum - 2 * curSum

``````class Solution {
public:
int minMoves2(vector<int>& nums) {
sort(nums.begin(), nums.end());
long long sum = accumulate(nums.begin(), nums.end(), 0);
long long res = LONG_MAX, curSum = 0;
int n = nums.size();
for (int i = 0; i < n; ++i) {
long long k = nums[i];
curSum += k;
res = min(res, 2 * k * (i + 1) - n * k + sum - 2 * curSum);
}
return res;
}
};
``````

Minimum Moves to Equal Array Elements

Best Meeting Point

https://discuss.leetcode.com/topic/68764/5-line-solution-with-comment

https://discuss.leetcode.com/topic/68884/c-average-o-n-nth_element-solution

https://discuss.leetcode.com/topic/68736/java-just-like-meeting-point-problem

https://discuss.leetcode.com/topic/68900/simple-c-sort-and-find-solution-with-detailed-explanation

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation