Minimum Moves to Equal Array Elements II - Problem
Given an integer array nums of size n, you need to find the minimum number of moves required to make all array elements equal.
In one move, you can increment or decrement any element of the array by exactly 1. Your goal is to transform all elements to the same value using the fewest possible moves.
Example: If you have [1,2,3], you could make all elements equal to 2 by decrementing 3 to 2 (1 move) and incrementing 1 to 2 (1 move), for a total of 2 moves.
Note: Test cases are designed so that the answer will fit in a 32-bit integer.
Input & Output
example_1.py โ Basic Case
$
Input:
[1,2,3]
โบ
Output:
2
๐ก Note:
The median is 2. We need |1-2| + |2-2| + |3-2| = 1 + 0 + 1 = 2 moves to make all elements equal to 2.
example_2.py โ Even Length Array
$
Input:
[1,10,2,9]
โบ
Output:
16
๐ก Note:
After sorting: [1,2,9,10]. The median can be either 2 or 9. Using 2 as target: |1-2| + |2-2| + |9-2| + |10-2| = 1 + 0 + 7 + 8 = 16 moves.
example_3.py โ Single Element
$
Input:
[1]
โบ
Output:
0
๐ก Note:
Array with single element is already equal. No moves needed.
Constraints
- n == nums.length
- 1 โค n โค 105
- -109 โค nums[i] โค 109
- The answer is guaranteed to fit in a 32-bit integer
Visualization
Tap to expand
Understanding the Visualization
1
Identify Positions
Friends are at houses 1, 2, and 3 on the street
2
Find Optimal Meeting Point
The median house (house 2) minimizes total walking distance
3
Calculate Total Distance
Friend at house 1 walks 1 step, friend at house 2 walks 0 steps, friend at house 3 walks 1 step
Key Takeaway
๐ฏ Key Insight: The median minimizes the sum of absolute deviations because it balances the 'pull' from both sides equally, making it the optimal meeting point for minimizing total movement.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code