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 arr into any number of contiguous subarrays and rearrange these subarrays in any order. This operation has a fixed cost of k.
  • Adjust element: 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.

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
Make Arrays Identical: Choose Best Strategy132arr:213brr:k = 1Strategy 1: DirectStrategy 2: Sort FirstCost: |1-2| + |3-1| + |2-3| = 4Sort both → [1,2,3] & [1,2,3]Cost: k + 0 = 1 + 0 = 1Minimum Cost: 1
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
Asked in
Google 15 Amazon 12 Microsoft 8
23.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen