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
Cost Function AnalysisTarget ValueTotal CostOptimal TargetHigh CostHigh CostKey Insight:Convex function hasexactly one minimumโ†’ Use ternary search!
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).
Asked in
Google 12 Amazon 8 Meta 6 Microsoft 4
28.4K Views
Medium Frequency
~25 min Avg. Time
890 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