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.

30:00

Minimum Moves to Equal Array Elements II
medium
Free written solution
Topics
Companies

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:
Input: {"nums":[1,2,3]}
Output: 2
Constraints:
  • n=nums.lengthn = \text{nums.length}

  • 1≤n≤1051 \leq n \leq 10^5

  • −109≤nums[i]≤109-10^9 \leq \text{nums[i]} \leq 10^9

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,2,3]}

A move changes one element by 1, up or down. All 3 elements must meet at one value. Which value is cheapest?

● current pair (i, j)━ closed pair: its span is its cost┊ median
123

moves so far (sum of closed pair spans)

0

Variables
VariableValue
n3
i-
j-
moves0
DepthFunction Call
Stack empty
0/5