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
Inputnums = [1,2,3]
Output2
Only two moves are needed: increment 1 to 2, then decrement 3 to 2, making all elements equal to 2.
Example 2
Inputnums = [1,10,2,9]
Output16
Making all elements equal to a median value requires 16 total increment or decrement moves.

Constraints

  • n == nums.length
  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

Asked at 5 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate