LeetCode solutions

3712. Minimum Cost to Make Arrays Identical

My accepted Python solution to LeetCode problem 3712, Minimum Cost to Make Arrays Identical, running in 240ms.

  • Difficulty: Medium
  • Python
  • Runtime 240ms
  • Memory 33.2MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 240ms, memory 33.2MB, accepted 2026-01-01.

python
class Solution:
    def minCost(self, arr: List[int], brr: List[int], k: int) -> int:
        n = len(arr)
        
        # Option 1: Don't split at all, just use element-wise operations
        cost_no_split = sum(abs(arr[i] - brr[i]) for i in range(n))
        
        # Option 2: Split and rearrange (costs k) + minimum matching cost
        # Minimum matching cost is achieved by sorting both arrays
        arr_sorted = sorted(arr)
        brr_sorted = sorted(brr)
        cost_with_split = k + sum(abs(arr_sorted[i] - brr_sorted[i]) for i in range(n))
        
        return min(cost_no_split, cost_with_split)

Source