Input: arr =[-7,9,5], brr =[7,-2,-5], k =2Output: 13Explanation:
* 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 is2.* Subtract 7 from element `arr[1]`. The array becomes `[7, -2, -7]`. The cost of this operation is7.* Add 2 to element `arr[2]`. The array becomes `[7, -2, -5]`. The cost of this operation is2.The total cost to make the arrays equal is`2 + 2 + 7 + 2 = 13`.
To make arr equal to brr, we can rearrange contiguous subarrays of arr at a fixed cost k, and then adjust each element to match brr using add/subtract operations. The optimal way is to sort both arrays and match elements directly, as rearrangement allows any order.
classSolution {
public:int minimumCost(vector<int>& arr, vector<int>& brr, int k) {
vector<int> a = arr, b = brr;
sort(a.begin(), a.end());
sort(b.begin(), b.end());
int ans = k;
for (int i =0; i < a.size(); ++i) ans += abs(a[i] - b[i]);
return ans;
}
};
classSolution {
publicintminimumCost(int[] arr, int[] brr, int k) {
int[] a = arr.clone(), b = brr.clone();
Arrays.sort(a);
Arrays.sort(b);
int ans = k;
for (int i = 0; i < a.length; ++i) ans += Math.abs(a[i]- b[i]);
return ans;
}
}
1
2
3
4
5
6
7
8
9
classSolution {
funminimumCost(arr: IntArray, brr: IntArray, k: Int): Int {
val a = arr.sorted()
val b = brr.sorted()
var ans = k
for (i in a.indices) ans += kotlin.math.abs(a[i] - b[i])
return ans
}
}
1
2
3
4
5
6
7
8
classSolution:
defminimumCost(self, arr: list[int], brr: list[int], k: int) -> int:
a = sorted(arr)
b = sorted(brr)
ans = k
for x, y in zip(a, b):
ans += abs(x - y)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
impl Solution {
pubfnminimum_cost(arr: Vec<i32>, brr: Vec<i32>, k: i32) -> i32 {
letmut a = arr.clone();
letmut b = brr.clone();
a.sort();
b.sort();
letmut ans = k;
for i in0..a.len() {
ans += (a[i] - b[i]).abs();
}
ans
}
}