website/content.en/ChapterFour/0400~0499/0462.Minimum-Moves-to-Equal-Array-Elements-II.md
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.
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 <= 10^5109 <= nums[i] <= 10^9Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where each move can increment or decrement one selected element by 1. You may assume that the length of the array is at most 10000.
package leetcode
import (
"math"
"sort"
)
func minMoves2(nums []int) int {
if len(nums) == 0 {
return 0
}
moves, mid := 0, len(nums)/2
sort.Ints(nums)
for i := range nums {
if i == mid {
continue
}
moves += int(math.Abs(float64(nums[mid] - nums[i])))
}
return moves
}