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.
Examples
Input:
nums = [1,2,3]Output:
2Explanation:
Move to 2: [2,2,2].
Input:
nums = [1,10,2,9]Output:
16Explanation:
The optimal target is the median. After sorting [1,2,9,10], the median is between 2 and 9, so it is possible to choose either. Using 2 as target: |1-2| + |10-2| + |2-2| + |9-2| = 1 + 8 + 0 + 7 = 16 moves.
Input:
nums = [5]Output:
0Explanation:
With only one element, all elements are already equal, so no moves are needed.
Constraints
- •
n == nums.length - •
1 ≤ nums.length ≤ 10^5