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: 1
💡 Note: Direct adjustment: |1-2| + |3-1| + |2-3| = 1 + 2 + 1 = 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: 5
💡 Note: Direct adjustment: |2-1| + |4-2| + |1-3| = 1 + 2 + 2 = 5. Sort cost: k + |1-1| + |2-2| + |4-3| = 10 + 0 + 0 + 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
Minimum Cost to Make Arrays Identical INPUT arr = [1, 3, 2] 1 3 2 brr = [2, 1, 3] 2 1 3 k = 1 k = 1 n = 3 (array length) Rearrange cost: k = 1 Modify cost: |diff| ALGORITHM STEPS 1 Strategy 1: No Rearrange Cost = |1-2| + |3-1| + |2-3| = 1 + 2 + 1 = 4 2 Strategy 2: With Rearrange Sort both arrays first sorted arr: [1,2,3] sorted brr: [1,2,3] 3 Calculate Sorted Cost Diff = |1-1|+|2-2|+|3-3| = 0 Total = k + 0 = 1 + 0 = 1 4 Compare Strategies min(4, 1) = 1 No rearrange: 4 With rearrange: 1 [BEST] Answer = min(4, 1) = 1 FINAL RESULT Optimal: Rearrange + Match Before (arr): 1 3 2 cost: k=1 After (sorted arr): 1 2 3 Target (sorted brr): 1 2 3 OK OK OK Output: 1 Key Insight: Compare Two Strategies 1. Without rearranging: Sum of |arr[i] - brr[i]| for all i (element-wise differences) 2. With rearranging: k + Sum of |sorted_arr[i] - sorted_brr[i]| (sorting minimizes total difference) Answer = min(Strategy1, Strategy2). Sorting both arrays optimally pairs smallest with smallest. TutorialsPoint - Minimum Cost to Make Arrays Identical | Compare Two Strategies Approach
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