Solution For Minimum Total Cost To Make Arrays Unequal
Problem Statement:
You are given n arrays a1,a2,…,an, where each ai contains ni integers.
You can perform the following operation any number of times:
Choose any two arrays (say a and b) with the same number of elements (let it be n).
Choose any two corresponding elements (say a[i] and b[i]).
Decrement a[i] and increment b[i].
Compute the total cost by taking the sum of absolute differences of all corresponding pairs of elements of all arrays.
The goal is to minimize the total cost. Determine the minimum total cost.
Solution:
The given problem can be solved by the following steps:
1. Count the total number of integers in the n arrays and check if they can be divided into n arrays such that each array contains the same number of integers. If not, return -1.
2. Sort all the arrays in increasing order.
3. Compute the median array (the array which has the median value of all the arrays).
4. Compute the absolute difference between each element of the median array and the corresponding element of other arrays to get the desired output.
Let’s discuss each step in detail.
Check if it is possible to divide the total number of integers in the n arrays into n equal parts:
If n does not divide the total number of integers in the n arrays evenly, then it is not possible to perform the given operation and hence the solution is not possible. Eg: if there are 4 arrays (n=4) and the total number of integers across the arrays is 10, then we cannot divide 10 integers into 4 equal parts.Sort all the arrays in increasing order:
Sorting the given arrays will help us in computing the median array in the next step. Bundling the corresponding elements of each array from low to high will also help in minimizing the absolute differences in the next step.Compute the median array:
The median array is the array with the value equal to the median element of all the arrays. There are a couple of ways to compute the median element. We can either sort all the elements and pick the middle element or we can use the two-pointer method. In the two-pointer method, we start with the very first element of each array and move towards the middle. Once we reach the middle, we can stop and consider the array that has the median value. If the number of integers is even, then we can pick any of the two arrays that have the middle values.Compute the absolute difference:
Once we have the median array, we can compute the absolute difference between each element of the median array and the corresponding element of other arrays. We will choose the absolute difference that leads to the minimum cost. The minimum cost can be computed by summing up all the absolute differences.
Code:
def min_moving_cost(arr):
# count total number of integers across all arrays
total_integers = sum([len(a) for a in arr])
# check if total number of integers can be divided into n arrays
if total_integers % len(arr) != 0:
return -1
# sort arrays in increasing order
arr.sort()
# compute median array
median = []
mid = total_integers // (2 * len(arr))
i, j = 0, mid
for k in range(mid):
if arr[i][k] < arr[-(i+1)][-(k+1)]:
median.append(arr[-(i+1)][-(k+1)])
arr[i][k], arr[-(i+1)][-(k+1)] = arr[-(i+1)][-(k+1)], arr[i][k]
else:
median.append(arr[i][k])
arr[i][k], arr[-(i+1)][-(k+1)] = arr[-(i+1)][-(k+1)], arr[i][k]
i += 1
# compute absolute difference
cost = 0
for a in arr:
for i in range(len(a)):
cost += abs(median[i] – a[i])
return cost
test the code
arr1 = [[1,2,3]]
arr2 = [[4,5,6]]
arr3 = [[0,0,1],[99,49,12],[11,11,11], [1, 1, 2]]
print(min_moving_cost(arr1)) # should return 3
print(min_moving_cost(arr2)) # should return 3
print(min_moving_cost(arr3)) # should return 137
Step by Step Implementation For Minimum Total Cost To Make Arrays Unequal
int minCostToMakeArrayUnequal(int[] nums) { // sort the array in ascending order Arrays.sort(nums); // initialize the minimum cost to make the arrays unequal to 0 int minCost = 0; // iterate through the array for (int i = 1; i < nums.length; i++) { // if the ith element is equal to the (i-1)th element, // we need to add 1 to the ith element to make the arrays unequal if (nums[i] == nums[i-1]) { nums[i]++; // increment the minimum cost by 1 minCost++; } // if the ith element is less than the (i-1)th element, // we need to add (i-1)th element - ith element to the ith element to make the arrays unequal else if (nums[i] < nums[i-1]) { minCost += nums[i-1] - nums[i]; nums[i] = nums[i-1]; } } return minCost; }
def minCostToMakeUnequal(costs): # Sort the array in ascending order costs.sort() # Get the length of the array n = len(costs) # Initialize minimum cost to 0 min_cost = 0 # Iterate over the array from the end for i in range(n-1, -1, -1): # If the ith element is greater than the (i-1)th element if costs[i] > costs[i-1]: # Increment the ith element by 1 costs[i] -= 1 # Add the current cost to the minimum cost min_cost += costs[i] # return the minimum cost return min_cost
var minCostToMakeArrayUnequal = function(costs) { // Sort the cost array in ascending order costs.sort((a, b) => a - b); // Initialize result let result = 0; // Iterate through the cost array for (let i = 0; i < costs.length - 1; i++) { // Add the ith element to the result result += costs[i]; } // Return the result return result; };
The minimum total cost to make arrays unequal is given by: Cost(i, j) = min(A[i] - A[j], B[i] - B[j]) Where A and B are the two arrays. We can compute the cost for all pairs of indices in O(N^2) time and O(1) space.
using System; public class Solution { public int MinimumCostToMakeArrayUnequal(int[] cost) { // sort the array in ascending order Array.Sort(cost); // initialize result int result = 0; // iterate through the array, starting from the second element for(int i = 1; i < cost.Length; i++) { // add the difference between the current element and the previous element to the result result += cost[i] - cost[i-1]; } // return the result return result; } }