Minimum Cost to Make Arrays Identical - Problem
You are given two integer arrays arr and brr of length n, and an integer k. Your goal is to transform arr to make it identical to brr using the minimum possible cost.
You have access to two types of operations:
- Rearrange Operation (Cost: k): Split
arrinto any number of contiguous subarrays and rearrange these subarrays in any order. This operation has a fixed cost ofk. - Modify Operation (Cost: x): Choose any element in
arrand add or subtract a positive integerxto it. The cost of this operation isx.
The key insight is that you can potentially use the rearrange operation to optimally pair elements from arr with elements from brr to minimize the total modification cost, but you need to decide whether the rearrangement cost k is worth it.
Return the minimum total cost to make arr equal to brr.
Input & Output
example_1.py โ Python
$
Input:
arr = [3, 1, 4], brr = [2, 4, 1], k = 2
โบ
Output:
3
๐ก Note:
Without rearrangement: |3-2| + |1-4| + |4-1| = 1 + 3 + 3 = 7. With optimal rearrangement: sort both arrays to get [1,3,4] and [1,2,4], giving cost |1-1| + |3-2| + |4-4| = 0 + 1 + 0 = 1, plus rearrangement cost k=2, total = 3. Since 3 < 7, answer is 3.
example_2.py โ Python
$
Input:
arr = [1, 2, 3], brr = [3, 2, 1], k = 10
โบ
Output:
4
๐ก Note:
Without rearrangement: |1-3| + |2-2| + |3-1| = 2 + 0 + 2 = 4. With rearrangement: both arrays become [1,2,3] when sorted, so modification cost = 0, but total = 0 + 10 = 10. Since 4 < 10, we choose not to rearrange. Answer is 4.
example_3.py โ Python
$
Input:
arr = [5], brr = [5], k = 1
โบ
Output:
0
๐ก Note:
Arrays are already identical, so no operations needed. Cost = 0.
Constraints
- 1 โค n โค 103
- 1 โค arr[i], brr[i] โค 106
- 1 โค k โค 109
- Arrays arr and brr have the same length n
Visualization
Tap to expand
Understanding the Visualization
1
Assess Current State
Calculate the cost of making arrays identical without any rearrangement
2
Find Optimal Configuration
Sort both arrays to determine the best possible element pairing
3
Calculate Reorganization Cost
Add the fixed rearrangement cost k to the optimal modification cost
4
Make Strategic Choice
Choose the strategy that gives minimum total cost
Key Takeaway
๐ฏ Key Insight: Sorting both arrays independently and pairing elements gives the mathematically minimum possible modification cost, but we must weigh this against the rearrangement cost k to make the optimal decision.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code