Minimum Cost to Make Array Equal Problem
Description
LeetCode Problem 2448.
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
numsby1.
The cost of doing one operation on the i^th element is cost[i].
Return the minimum total cost such that all the elements of the array nums become equal.
Example 1:
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 0^th element one time. The cost is 2.
- Decrease the 1^st element one time. The cost is 3.
- Decrease the 2^nd 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.
Example 2:
Input: nums = [2,2,2,2,2], cost = [4,2,8,1,3]
Output: 0
Explanation: All the elements are already equal, so no operations are needed.
Constraints:
n == nums.length == cost.length1 <= n <= 10^51 <= nums[i], cost[i] <= 10^6- Test cases are generated in a way that the output doesn't exceed 2^53-1
Solution
Approach: Sorting + Prefix Sums
Sort the pairs (nums[i], cost[i]) by value. If every element becomes x, the total cost is the sum of |nums[i] - x| * cost[i], and the best x is always one of the existing values.
Splitting the sum at x, the elements at or below x cost x * (sum of their costs) - (sum of nums * cost), and the elements above cost (sum of nums * cost) - x * (sum of their costs). Prefix sums of cost and of nums * cost give both parts in O(1), so we try every value as x and keep the minimum.
Complexity: O(n log n) time, dominated by sorting, and O(n) space.
from math import inf
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