Minimum Cost to Make Arrays Identical - Problem
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 and rearrange: Split
arrinto any number of contiguous subarrays and rearrange these subarrays in any order. This operation has a fixed cost ofk. - Adjust element: 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.
Input & Output
Example 1 — Basic Case
$
Input:
arr = [1,3,2], brr = [2,1,3], k = 1
›
Output:
2
💡 Note:
Direct adjustment: |1-2| + |3-1| + |2-3| = 4. Sort both arrays: [1,2,3] and [1,2,3], cost = k + 0 = 1. Minimum is 1.
Example 2 — High Rearrangement Cost
$
Input:
arr = [2,4,1], brr = [1,2,3], k = 10
›
Output:
4
💡 Note:
Direct adjustment: |2-1| + |4-2| + |1-3| = 1 + 2 + 2 = 5. Sort cost: k + |1-1| + |2-2| + |4-3| = 10 + 1 = 11. Choose direct adjustment: 5.
Example 3 — Already Optimal
$
Input:
arr = [1,2,3], brr = [1,2,3], k = 5
›
Output:
0
💡 Note:
Arrays are already identical, no operations needed. Cost = 0.
Constraints
- 1 ≤ n ≤ 105
- -106 ≤ arr[i], brr[i] ≤ 106
- 1 ≤ k ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input
Two arrays arr and brr, and rearrangement cost k
2
Process
Compare direct adjustment vs sort + adjust strategies
3
Output
Minimum cost to make arrays identical
Key Takeaway
🎯 Key Insight: Compare direct adjustment cost vs k + optimal pairing cost after sorting
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code