3424. Minimum Cost to Make Arrays Identical
Description
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 
arrinto 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 <= 1050 <= k <= 2 * 1010-105 <= arr[i] <= 105-105 <= brr[i] <= 105
Solutions
Solution 1: Greedy + Sorting
If splitting the array is not allowed, we can directly calculate the sum of absolute differences between the two arrays as the total cost \(c_1\). If splitting is allowed, we can divide the array \(\textit{arr}\) into \(n\) subarrays of length 1, then rearrange them in any order, and compare with array \(\textit{brr}\), calculating the sum of absolute differences as the total cost \(c_2\). To minimize \(c_2\), we can sort both arrays and then calculate the sum of absolute differences. The final result is \(\min(c_1, c_2 + k)\).
The time complexity is \(O(n \times \log n)\), and the space complexity is \(O(\log n)\), where \(n\) is the length of the array \(\textit{arr}\).
1 2 3 4 5 6 7  |  | 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17  |  | 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17  |  | 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20  |  | 
1 2 3 4 5 6 7 8 9 10 11 12 13 14  |  | 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18  |  |