Algorithm
Problem Name: 462. Minimum Moves to Equal Array Elements II
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.
Example 1:
Input: nums = [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]
Example 2:
Input: nums = [1,10,2,9] Output: 16
Constraints:
n == nums.length1 <= nums.length <= 105-109 <= nums[i] <= 109
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
public int minMoves2(int[] nums) {
Arrays.sort(nums);
int sum = 0;
int start = 0;
int end = nums.length - 1;
while (start < end) {
sum += nums[end--] - nums[start++];
}
return sum;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const minMoves2 = function(nums) {
nums.sort((a, b) => a - b);
let i = 0,
j = nums.length - 1;
let res = 0;
while (i < j) {
res += nums[j] - nums[i];
i++;
j--;
}
return res;
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def minMoves2(self, nums):
nums.sort()
m = nums[(len(nums) - 1) // 2]
return sum(abs(num - m) for num in nums)
Copy The Code &
Try With Live Editor
Input
Output