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
numsby 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:
18
💡 Note:
Optimal target is 10: cost = |1-10|×1 + |10-10|×1 + |20-10|×1 = 9 + 0 + 9 = 18
Constraints
- n == nums.length
- n == cost.length
- 1 ≤ n ≤ 105
- 1 ≤ nums[i], cost[i] ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input Arrays
nums = [1,3,5] with costs = [2,3,1]
2
Find Target
Optimal target is weighted median = 3
3
Calculate Cost
Total cost = |1-3|×2 + |3-3|×3 + |5-3|×1 = 6
Key Takeaway
🎯 Key Insight: The optimal target is the weighted median, minimizing total movement cost
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code