Minimum Cost to Make Array Equal - Problem
Imagine you're a data analyst tasked with standardizing measurement readings from different sensors. You have an array nums representing the current readings and an array cost representing how expensive it is to adjust each sensor.
Your goal is to make all sensor readings equal with minimum total cost. You can increase or decrease any element in nums by 1, but each operation on the i-th element costs cost[i].
Example: If nums = [1, 3, 5, 2] and cost = [2, 3, 1, 14], you need to find the target value that minimizes the total adjustment cost.
Return the minimum total cost to make all elements equal.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [1, 3, 5, 2], cost = [2, 3, 1, 14]
โบ
Output:
8
๐ก Note:
We can make all elements equal to 2. Cost = |1-2|ร2 + |3-2|ร3 + |5-2|ร1 + |2-2|ร14 = 2 + 3 + 3 + 0 = 8
example_2.py โ All Equal
$
Input:
nums = [2, 2, 2, 2], cost = [4, 2, 8, 1]
โบ
Output:
0
๐ก Note:
All elements are already equal, so no operations are needed. Total cost = 0
example_3.py โ Large Costs
$
Input:
nums = [1, 4], cost = [1, 100]
โบ
Output:
3
๐ก Note:
Better to move element at index 0 to 4: cost = |1-4|ร1 + |4-4|ร100 = 3 + 0 = 3. Moving the expensive element would cost 300.
Constraints
- n == nums.length == cost.length
- 1 โค n โค 105
- 1 โค nums[i], cost[i] โค 106
- All elements can be negative after operations
Visualization
Tap to expand
Understanding the Visualization
1
Plot Cost Function
For each possible target, calculate total adjustment cost
2
Identify Convex Shape
Cost function forms a bowl - decreases to minimum, then increases
3
Apply Ternary Search
Use ternary search to efficiently find the bottom of the bowl
Key Takeaway
๐ฏ Key Insight: The total cost function is convex (unimodal), meaning it has exactly one minimum point. This allows us to use ternary search instead of brute force, reducing time complexity from O(n ร range) to O(n log range).
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code