Skip to problem
←

Minimum Cost to Equalize an Array

Medium 0 attempts

Given an integer array arr, choose a common integer target and change every element to that value. Changing a value from a to b costs |a - b|.

Return the minimum sum of these costs, not the target value. The target may be any integer; you do not have to choose an existing array element. Multiple targets may achieve the same minimum cost.

For [1,100,101], choosing 100 costs 99 + 0 + 1 = 100. For [1,10], any integer target from 1 through 10 gives cost 9.

Function contract

Implement makeAllArrayElementsEqualWithMinimumCost(arr). Receive a nonempty array of positive integers.

Output: Return the minimum total cost as a number, not the chosen target value.

Example 1

Input
arr = [1,100,101]
Output
100

Example 2

Input
arr = [5,5]
Output
0
Constraints
  • 1 <= arr.length <= 10^5
  • 1 <= arr[i] <= 10^5
Topics

Approach: Sort + Median

Copy and sort the array, then pick the median element as the target. The median minimizes the sum of absolute deviations. For an even number of elements, any value between the two middle values is optimal; choosing the upper median suffices. Moving the target toward the middle decreases the distances on the larger side at least as fast as it increases distances on the smaller side. Compute the total cost as the sum of absolute differences from the median.

javascript
function makeAllArrayElementsEqualWithMinimumCost(arr) {
  const sorted = [...arr].sort((a, b) => a - b);
  const median = sorted[Math.floor(sorted.length / 2)];
  return arr.reduce((sum, x) => sum + Math.abs(x - median), 0);
}

Time Complexity: O(n log n)

Space Complexity: O(n) for the sorted copy and sorting workspace.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript