[LeetCode] Minimum Cost to Make Arrays Identical

3424. Minimum Cost to Make Arrays Identical

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 arr into any number of contiguous subarrays and rearrange these subarrays in any order. This operation has a fixed cost of k.
  • Choose any element in arr and add or subtract a positive integer x to it. The cost of this operation is x.

Return the minimum total cost to make arr equal to brr.

A subarray is a contiguous non-empty sequence of elements within an array.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
long long minCost(vector<int>& arr, vector<int>& brr, long long k) {
long long res = 0, n = arr.size(), ans = k;
for(int i = 0; i < n; i++) res += abs(arr[i] - brr[i]);
sort(begin(arr), end(arr));
sort(begin(brr), end(brr));
for(int i = 0; i < n; i++) ans += abs(arr[i] - brr[i]);
return min(res,ans);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/01/19/PS/LeetCode/minimum-cost-to-make-arrays-identical/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.