Facebook Pixel

3424. Minimum Cost to Make Arrays Identical


Problem Description

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:

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

Intuition

The primary goal is to make the elements of arr equal to the elements of brr at minimal cost. To achieve this, we consider two possible strategies:

  1. Direct Transformation: Calculate the cost of transforming elements in arr directly to the corresponding elements in brr using the operation of adding or subtracting a positive integer x. This cost is straightforwardly computed as the sum of absolute differences between corresponding elements of arr and brr.

  2. Reordering with Splitting: Another approach is to potentially reorder arr to better match brr after sorting both arrays and possibly split arr into subarrays. The cost for this strategy includes the fixed operation cost k (for any number of splits and reordering), plus the cost of aligning the sorted version of arr to the sorted version of brr.

The solution involves computing both costs (c1 for the direct transformation cost and c2 for the reordering with splitting strategy) and selecting the minimum of these costs. This choice leverages the fact that reordering arr can sometimes align it more closely to brr with minimal cost, particularly when the fixed cost k is offset by reduced alignment costs.

Learn more about Greedy and Sorting patterns.

Solution Approach

The solution is implemented through a structured approach consisting of the following steps:

  1. Calculate Direct Transformation Cost (c1):

    • Use a loop to iterate over paired elements of arr and brr.
    • Compute the sum of absolute differences for each pair. This value represents the minimal cost needed to convert arr directly into brr without any reordering.
    c1 = sum(abs(a - b) for a, b in zip(arr, brr))
  2. Sort and Reorder Arrays:

    • Sort both arr and brr to minimize the cost when computing their difference post-reordering.
    • This operation facilitates easier alignment by comparing elements at identical indices, thus minimizing conversion costs.
    arr.sort()
    brr.sort()
  3. Calculate Reordering Cost with Splitting (c2):

    • The cost includes the fixed splitting and reordering cost k.
    • Add the minimum transformation cost after sorting, which is the sum of absolute differences between the sorted versions of the arrays.
    c2 = k + sum(abs(a - b) for a, b in zip(arr, brr))
  4. Choose the Minimum Cost:

    • Compare the two calculated costs, c1 and c2, and return the smaller value.
    • This ensures choosing the most cost-effective approach to make arr equal to brr.
    return min(c1, c2)

This method efficiently utilizes sorting to capitalize on potential reordering benefits and incorporates the use of absolute differences to determine the transformation costs precisely, thus providing an optimal solution to the problem.

Ready to land your dream job?

Unlock your dream job with a 2-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's consider a small example to illustrate the solution approach:

Suppose we have the following inputs:

  • arr = [1, 3, 5]
  • brr = [2, 4, 6]
  • k = 3

We'll use the described solution approach to determine the minimum total cost to make arr equal to brr.

  1. Calculate Direct Transformation Cost (c1):

    • For each pair of elements (from arr and brr): compute the absolute difference.
    • Here, the differences are |1 - 2| = 1, |3 - 4| = 1, |5 - 6| = 1.
    • Sum these differences: c1 = 1 + 1 + 1 = 3.

    Thus, c1 is 3.

  2. Sort and Reorder Arrays:

    • Sort arr: [1, 3, 5] (already sorted)
    • Sort brr: [2, 4, 6] (already sorted)
  3. Calculate Reordering Cost with Splitting (c2):

    • The fixed cost for any reordering operation is k, which is 3.
    • Compute the absolute differences of sorted arr and brr: |1 - 2| = 1, |3 - 4| = 1, |5 - 6| = 1.
    • Sum these differences and add the fixed cost k: c2 = 3 + (1 + 1 + 1) = 3 + 3 = 6.
  4. Choose the Minimum Cost:

    • Compare c1 and c2:
    • Since c1 (3) < c2 (6), the minimal cost is 3.

The optimal strategy is the Direct Transformation without any reordering in this case, costing a total of 3.

Solution Implementation

1from typing import List
2
3class Solution:
4    def minCost(self, arr: List[int], brr: List[int], k: int) -> int:
5        # Calculate the initial cost as the sum of absolute differences of corresponding elements
6        c1 = sum(abs(a - b) for a, b in zip(arr, brr))
7      
8        # Sort both arrays
9        arr.sort()
10        brr.sort()
11      
12        # Calculate the alternative cost with the sorted arrays plus a constant k
13        c2 = k + sum(abs(a - b) for a, b in zip(arr, brr))
14      
15        # Return the minimum of the two calculated costs
16        return min(c1, c2)
17
1import java.util.Arrays;
2
3class Solution {
4    public long minCost(int[] arr, int[] brr, long penaltyCost) {
5        // Calculate initial cost without sorting
6        long initialCost = calc(arr, brr);
7      
8        // Sort both arrays to potentially minimize cost
9        Arrays.sort(arr);
10        Arrays.sort(brr);
11      
12        // Calculate sorted cost with additional penalty
13        long sortedCostWithPenalty = calc(arr, brr) + penaltyCost;
14      
15        // Return the minimum of initial cost or sorted cost with penalty
16        return Math.min(initialCost, sortedCostWithPenalty);
17    }
18
19    private long calc(int[] arr, int[] brr) {
20        long totalCost = 0;
21      
22        // Iterate through both arrays to calculate the sum of absolute differences
23        for (int i = 0; i < arr.length; ++i) {
24            totalCost += Math.abs(arr[i] - brr[i]);
25        }
26      
27        return totalCost;
28    }
29}
30
1#include <vector>
2#include <algorithm>
3#include <cmath>
4#include <numeric>
5
6class Solution {
7public:
8    long long minCost(std::vector<int>& arr, std::vector<int>& brr, long long k) {
9        // Lambda to calculate the total pairwise absolute difference between two arrays
10        auto calculateDifference = [](const std::vector<int>& arr, const std::vector<int>& brr) {
11            long long totalDifference = 0;
12            for (size_t i = 0; i < arr.size(); ++i) {
13                totalDifference += std::abs(arr[i] - brr[i]);
14            }
15            return totalDifference;
16        };
17
18        // Calculate the cost without sorting
19        long long originalCost = calculateDifference(arr, brr);
20
21        // Sort both arrays
22        std::sort(arr.begin(), arr.end());
23        std::sort(brr.begin(), brr.end());
24
25        // Calculate the cost with sorted arrays and add k to it
26        long long sortedCost = calculateDifference(arr, brr) + k;
27
28        // Return the minimum of the original cost and the sorted cost
29        return std::min(originalCost, sortedCost);
30    }
31};
32
1// Function to calculate the minimum cost to make two arrays equal by using at most k operations
2function minCost(arr: number[], brr: number[], k: number): number {
3  
4    // Helper function to calculate the sum of absolute differences between two arrays
5    const calc = (a: number[], b: number[]): number => {
6        let totalCost = 0;
7        for (let i = 0; i < a.length; ++i) {
8            totalCost += Math.abs(a[i] - b[i]);
9        }
10        return totalCost;
11    };
12
13    // Calculate the cost without any modification
14    const c1 = calc(arr, brr);
15
16    // Sort both arrays to find the optimal matching pairing elements in a sorted order
17    arr.sort((a, b) => a - b);
18    brr.sort((a, b) => a - b);
19
20    // Calculate the cost with the sorted arrays plus the extra allowed operations cost
21    const c2 = calc(arr, brr) + k;
22  
23    // Return the minimum of the two calculated costs
24    return Math.min(c1, c2);
25}
26

Time and Space Complexity

The time complexity of the code is mainly determined by two parts: the computation of the initial cost and the sorting operations.

  1. Computation of Initial Cost (c1):

    • The computation of c1 involves iterating over both lists using zip and calculating the absolute difference for each pair. This operation is O(n) where n is the length of the lists.
  2. Sorting:

    • Sorting both arr and brr involves O(n log n) time complexity since sorting an array of n elements is O(n log n).
  3. Computation of Sorted Cost (c2):

    • After sorting, the computation of c2 involves a similar operation as c1, iterating over both lists and calculating the absolute difference for each pair. This costs O(n) as well.

Finally, the computation involves taking the minimum of c1 and c2, which is a constant-time operation O(1).

Therefore, the overall time complexity of the code is O(n log n).

The space complexity of the code is O(1), as the algorithm uses only a constant amount of additional space besides the input and output, primarily for variables like c1 and c2.

Learn more about how to find time and space complexity quickly.


Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:
Question 1 out of 10

Consider the classic dynamic programming of longest increasing subsequence:

Find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order.

For example, the length of LIS for [50, 3, 10, 7, 40, 80] is 4 and LIS is [3, 7, 40, 80].

What is the recurrence relation?


Recommended Readings

Want a Structured Path to Master System Design Too? Donโ€™t Miss This!


Load More