Minimum Cost to Make Arrays Identical Problem
Description
LeetCode Problem 3424.
You are given two integer arrays arr and brr of length n, and an integer k. You can perform the following operations on arr any number of times:
- Split
arrinto any number of contiguous subarrays and rearrange these subarrays in any order. This operation has a fixed cost ofk. - Choose any element in
arrand add or subtract a positive integerxto it. The cost of this operation isx.
Return the minimum total cost to make arr equal to brr.
Example 1:
Input: arr = [-7,9,5], brr = [7,-2,-5], k = 2
Output: 13
Explanation:
- Split arr into two contiguous subarrays: [-7] and [9, 5] and rearrange them as [9, 5, -7], with a cost of 2.
- Subtract 2 from element arr[0]. The array becomes [7, 5, -7]. The cost of this operation is 2.
- Subtract 7 from element arr[1]. The array becomes [7, -2, -7]. The cost of this operation is 7.
- Add 2 to element arr[2]. The array becomes [7, -2, -5]. The cost of this operation is 2.
The total cost to make the arrays equal is 2 + 2 + 7 + 2 = 13.
Example 2:
Input: arr = [2,1], brr = [2,1], k = 0
Output: 0
Explanation:
Since the arrays are already equal, no operations are needed, and the total cost is 0.
Constraints:
1 <= arr.length == brr.length <= 10^50 <= k <= 2 * 10^10-10^5 <= arr[i] <= 10^5-10^5 <= brr[i] <= 10^5
Solution
Approach: Greedy + Sorting
There are two ways to finish. Without rearranging, we change each arr[i] into brr[i], which costs the sum of |arr[i] - brr[i]|; call it c1.
A split costs k and can cut arr into as many pieces as we like, so one split already allows any reordering (cut into single elements). The best order matches the sorted arr with the sorted brr, and the cost is again a sum of absolute differences, plus k for the split. More splits would only add cost. The answer is the smaller of the two options.
Complexity: O(n log n) time and O(1) extra space beyond the sort.
class Solution:
def minCost(self, arr: List[int], brr: List[int], k: int) -> int:
c1 = sum(abs(a - b) for a, b in zip(arr, brr))
arr.sort()
brr.sort()
c2 = k + sum(abs(a - b) for a, b in zip(arr, brr))
return min(c1, c2)