#3424

Minimum Cost to Make Arrays Identical

Medium
ArrayGreedySortingGreedySorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the fact that rearranging subarrays allows us to minimize the cost of adjustments. By calculating the total cost of adjustments and comparing it with the fixed cost of rearranging, we can determine the minimum cost efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the total adjustment cost by summing the absolute differences between `arr[i]` and `brr[i]`.
  2. 2Step 2: Compare the total adjustment cost with the fixed cost `k`.
  3. 3Step 3: Return the minimum of the total adjustment cost and the total adjustment cost plus `k`.
solution.py3 lines
1def minCost(arr, brr, k):
2    totalAdjustmentCost = sum(abs(arr[i] - brr[i]) for i in range(len(arr)))
3    return min(totalAdjustmentCost, totalAdjustmentCost + k)

Complexity note: This complexity is linear because we only traverse the arrays once to compute the total adjustment cost. The space complexity is constant since we are not using any additional data structures.

  • 1Rearranging subarrays can help minimize the total adjustment cost.
  • 2The fixed cost of rearranging can be compared against the total adjustment cost to find the minimum.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.