142. Minimum Moves to Equal Array Elements II

HardArrayArray

Given an integer array nums, return the minimum number of moves to make all elements equal, where each move increments or decrements one element by 1. The optimal target is the median.

Input: An integer array.

Output: Integer — minimum moves.

Examples

Example 1
Input: [1,2,3]
Output: 2
Explanation: Move to 2: |1-2|+|3-2|=2.
Example 2
Input: [1,10,2,9]
Output: 16
Explanation: Median-based total.
Example 3
Input: [1]
Output: 0
Explanation: Single element.

Constraints

Asked by

MicrosoftGoogleAmazon
Solve this problem in the editor →