Minimum Cost to Make Array Equal - Problem

You are given two 0-indexed arrays nums and cost consisting each of n positive integers.

You can do the following operation any number of times:

  • Increase or decrease any element of the array nums by 1.

The cost of doing one operation on the ith element is cost[i].

Return the minimum total cost such that all the elements of the array nums become equal.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,3,5], cost = [2,3,1]
Output: 6
💡 Note: Change nums to [3,3,3]: cost = |1-3|×2 + |3-3|×3 + |5-3|×1 = 2×2 + 0×3 + 2×1 = 6
Example 2 — Equal Elements
$ Input: nums = [2,2,2,2], cost = [4,2,8,1]
Output: 0
💡 Note: All elements are already equal, so no operations needed. Total cost = 0
Example 3 — Large Range
$ Input: nums = [1,10,20], cost = [1,1,1]
Output: 19
💡 Note: Optimal target is 10: cost = |1-10|×1 + |10-10|×1 + |20-10|×1 = 9 + 0 + 10 = 19

Constraints

  • n == nums.length
  • n == cost.length
  • 1 ≤ n ≤ 105
  • 1 ≤ nums[i], cost[i] ≤ 106

Visualization

Tap to expand
Minimum Cost to Make Array Equal Weighted Median Approach INPUT nums array 1 i=0 3 i=1 5 i=2 cost array 2 3 1 nums = [1, 3, 5] cost = [2, 3, 1] Total cost weight: 2+3+1 = 6 Half weight = 3 ALGORITHM STEPS 1 Sort by nums values Pair (num, cost) and sort (1,2), (3,3), (5,1) 2 Find weighted median Cumulative cost >= half cum: 2 --> 2+3=5 --> 5+1=6 Median at nums[1] = 3 3 Calculate total cost Sum |num - median| * cost 4 Compute costs |1-3|*2=4, |3-3|*3=0 |5-3|*1=2 Total = 4 + 0 + 2 = 6 FINAL RESULT Target Value (Median) 3 All elements become 3 3 3 3 1 --> 3: 2 steps * cost 2 = 4 3 --> 3: 0 steps * cost 3 = 0 5 --> 3: 2 steps * cost 1 = 2 Output: 6 OK - Minimum cost achieved Key Insight: The weighted median minimizes the total weighted distance. Unlike simple median, we consider each element's cost as its "weight". The optimal target is where cumulative weight first exceeds half of total. Time: O(n log n) for sorting. Space: O(n) for storing pairs. TutorialsPoint - Minimum Cost to Make Array Equal | Weighted Median Approach
Asked in
Google 12 Amazon 8 Microsoft 6
18.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen