Leetcode #2448: Minimum Cost to Make Array Equal
In this guide, we solve Leetcode #2448 Minimum Cost to Make Array Equal in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Greedy, Array, Binary Search, Prefix Sum, Sorting
Intuition
The problem structure suggests a monotonic decision, which makes binary search a natural fit.
By halving the search space each step, we reach the answer efficiently.
Approach
Search either directly on a sorted array or on the answer space using a check function.
Each check is fast, and the logarithmic search keeps the overall runtime low.
Steps:
- Define the search bounds.
- Check the mid point condition.
- Narrow the bounds until convergence.
Example
Input: nums = [1,3,5,2], cost = [2,3,1,14]
Output: 8
Explanation: We can make all the elements equal to 2 in the following way:
- Increase the 0th element one time. The cost is 2.
- Decrease the 1st element one time. The cost is 3.
- Decrease the 2nd element three times. The cost is 1 + 1 + 1 = 3.
The total cost is 2 + 3 + 3 = 8.
It can be shown that we cannot make the array equal with a smaller cost.
Python Solution
class Solution:
def minCost(self, nums: List[int], cost: List[int]) -> int:
arr = sorted(zip(nums, cost))
n = len(arr)
f = [0] * (n + 1)
g = [0] * (n + 1)
for i in range(1, n + 1):
a, b = arr[i - 1]
f[i] = f[i - 1] + a * b
g[i] = g[i - 1] + b
ans = inf
for i in range(1, n + 1):
a = arr[i - 1][0]
l = a * g[i - 1] - f[i - 1]
r = f[n] - f[i] - a * (g[n] - g[i])
ans = min(ans, l + r)
return ans
Complexity
The time complexity is , where is the length of the array nums. The space complexity is O(1).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.