Minimum Cost to Make Array Equal

Updated on 16 June, 2025
Minimum Cost to Make Array Equal header image

Problem Statement

In this problem, you are provided with two arrays: nums and cost, both of size n and filled with positive integers. The array nums represents a sequence of numbers, while cost details the cost associated with modifying each corresponding element in nums.

The available operation allows you to either increment or decrement an element in nums by 1, with the modification cost of manipulating the i-th element given as cost[i]. Your objective is to determine the smallest possible cumulative cost to make all entries in nums uniform (i.e., all entries are the same).

The challenge is to compute this minimum cost efficiently, considering the constraints on the length of the arrays and the values they hold.

Examples

Example 1

Input:

nums = [1,3,5,2], cost = [2,3,1,14]

Output:

8

Explanation:

We can make all the elements equal to 2 in the following way:
- Increase the 0th element one time. The cost is 2.
- Decrease the 1st element one time. The cost is 3.
- Decrease the 2nd element three times. The cost is 1 + 1 + 1 = 3.
The total cost is 2 + 3 + 3 = 8.
It can be shown that we cannot make the array equal with a smaller cost.

Example 2

Input:

nums = [2,2,2,2,2], cost = [4,2,8,1,3]

Output:

0

Explanation:

All the elements are already equal, so no operations are needed.

Constraints

  • n == nums.length == cost.length
  • 1 <= n <= 105
  • 1 <= nums[i], cost[i] <= 106
  • Test cases are generated in a way that the output doesn't exceed 253-1

Approach and Intuition

The problem essentially boils down to finding a target value in the nums array that can be attained from all other numbers at the lowest total modification cost, given the cost for changing each element is specific and listed in cost.

  1. Understanding the relation between cost and the value adjustments:

    • Since each element can be adjusted by increasing or decreasing its value at a specific cost, you should aim at adjusting all the values in nums to a common target that minimizes the sum of these costs.
  2. Analyzing sample cases for patterns:

    • In the first example, adjusting all numbers to 2 was optimal. Meanwhile, in the second example, since all elements were already the same, no cost was necessary.
  3. Determining the target value:

    • An effective strategy is to consider changing every number in nums to one common value and calculate the required cost for each potential target.
    • This target could be derived based on the mean or the median of the numbers factored by their respective costs, as these statistical measures often represent central tendencies which could be nearer to the cost-effective target.
  4. Calculating the cost for adjusting each potential target:

    • Iterate through each number in nums, calculate the difference from the current target, multiply this by its respective cost in cost, and sum these values.
    • Due to the potentially large size of n, this operation should be as optimized as possible, likely necessitating an algorithm that runs in linear or linearithmic time relative to n.
  5. Concluding the minimum total cost:

    • The minimum out of all calculated total costs for possible targets gives the desired answer.

It's essential to identify an efficient way to manage large inputs and outputs, as per the constraints, while calculating the cumulative costs dynamically to avoid recalculating from scratch for each potential target. This means using pre-computed sums or similar techniques to optimize the calculations.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    long long calculateTotalCost(vector<int>& elements, vector<int>& adjustments, int value) {
        long long total = 0;
        for (int index = 0; index < elements.size(); ++index)
            total += 1L * abs(elements[index] - value) * adjustments[index];
        return total;
    }
        
    long long findMinCost(vector<int>& elements, vector<int>& adjustments) {
        long long minimalCost = calculateTotalCost(elements, adjustments, elements[0]);
        int lowerBound = *min_element(elements.begin(), elements.end());
        int upperBound = *max_element(elements.begin(), elements.end());
            
        while (lowerBound < upperBound) {
            int middle = (lowerBound + upperBound) / 2;
            long long costLeft = calculateTotalCost(elements, adjustments, middle);
            long long costRight = calculateTotalCost(elements, adjustments, middle + 1);
            minimalCost = min(costLeft, costRight);
            if (costLeft > costRight)
                lowerBound = middle + 1;
            else
                upperBound = middle;
        }
        return minimalCost;
    } 
};

The problem titled "Minimum Cost to Make Array Equal" involves finding a way to minimize cost tied to modifying values of an array to make them all equal. The cost function demands adjusting original array elements to a target value, multiplied by a specified adjustment factor for each element. Using C++, the solution employs an efficient strategy, possibly a binary search, to determine the minimum cost.

The provided code defines a C++ class with methods to calculate the total cost of adjusting the elements to a specific value and finding the minimal cost to transform all array elements to the same value:

  • calculateTotalCost method: This function calculates the total cost of changing each element in an array (elements) to a specific value (value), factoring in the unique adjustment costs (adjustments) for each element. The cost for each element is the absolute difference between the element's current value and the target value, multiplied by the element's respective adjustment.

  • findMinCost method: This function determines the minimum cost to make all elements in the array identical. It first initializes the minimal cost to the cost of converting all elements to the value of the first element in elements. Next, the method proceeds to identify bounds (lowerBound and upperBound) representing the smallest and largest values in elements, respectively. This sets up for a binary search within these bounds to find the optimal target value that results in the minimum total adjustment cost. The binary search iteratively refines the target value by comparing costs at midpoints (average of current bounds) and adjusting bounds based on which split (left or right of the midpoint) offers a lower cost.

The precise implementation of minimum search ensures that both time complexity and computational costs are optimized by reducing the number of necessary calculations, specifically targeted towards scenarios where adjustments could potentially be extensive or costly. This approach significantly streamlines the process in terms of complexity and operational efficiency, making it a suitable solution for large datasets and performance-critical applications.

java
class Solution {
    // Calculate the total cost based on a target value.
    private long calculateTotalCost(int[] elements, int[] weights, int target) {
        long totalCost = 0L;
        for (int i = 0; i < elements.length; i++) {
            totalCost += 1L * Math.abs(elements[i] - target) * weights[i];
        }
        return totalCost;
    }
    
    public long minimumCost(int[] elements, int[] weights) {
        // Set search bounds for the optimal target value.
        int minElement = 1000001, maxElement = 0;
        for (int element : elements) {
            minElement = Math.min(minElement, element);
            maxElement = Math.max(maxElement, element);
        }
        long minCost = calculateTotalCost(elements, weights, elements[0]);
    
        // Binary search to find the optimal target that minimizes costs.
        while (minElement < maxElement) {
            int current = (maxElement + minElement) / 2;
            long costCurrent = calculateTotalCost(elements, weights, current);
            long costNext = calculateTotalCost(elements, weights, current + 1);
            minCost = Math.min(costCurrent, costNext);
    
            if (costCurrent > costNext) 
                minElement = current + 1;
            else
                maxElement = current;
        }
        return minCost;
    }
}

The solution provided in Java addresses the problem of finding the minimum cost to make all elements in an array equal when each element has a specific weighting. The approach involves minimizing the total cost, defined as the sum of the absolute differences between each array element and a target value, multiplied by the weight of each element.

Here's an overview of how the code operates:

  • Calculate Total Cost Function:

    • Develop a method (calculateTotalCost) that computes the total cost of converting all elements in the array to a given target value.
    • Iterate through each element in the array, calculate the difference between the element and the target, multiply this by the element's weight, then sum these values for the final cost.
  • Main Function (minimumCost):

    • Initialize boundaries for possible target values using the maximum and minimum elements in the array.
    • Use binary search to efficiently find the target value that results in the minimal total cost:
      • Determine the middle value of the current search range as a potential target, and calculate the associated total cost.
      • Compare this cost with the cost of the next sequential target (middle value + 1).
      • Adjust the search boundaries based on which target yields a lower cost.
    • Continue narrowing the search range until the optimal target is found.

This solution leverages binary search on the potential target values, significantly optimizing the process by reducing the number of necessary calculations compared to a brute-force approach. Additionally, the initial assessment of the possible range of target values ensures that every potential minimum or maximum is considered. This guarantees that even in skewed distributions of element values, the algorithm effectively locates the target that minimizes the cost.

python
class Solution:
    def minimumCost(self, values: List[int], weights: List[int]) -> int:
        # Compute the cost to equalize all elements to a target value.
        def total_cost(target):
            return sum(abs(target - val) * weight for val, weight in zip(values, weights))
            
        # Define search range.
        low, high = min(values), max(values)
        optimal_cost = total_cost(values[0])
            
        # Binary search to find the value with minimum cost.
        while low < high:
            mid_point = (low + high) // 2
            cost_mid = total_cost(mid_point)
            cost_mid_plus_one = total_cost(mid_point + 1)
            optimal_cost = min(cost_mid, cost_mid_plus_one)
                
            if cost_mid > cost_mid_plus_one:
                low = mid_point + 1
            else:
                high = mid_point
            
        return optimal_cost

This Python solution addresses the problem of finding the minimum cost to make all elements of an array equal when each element has an associated weight influencing the cost of changing that element.

  • Start by defining a function total_cost inside the minimumCost method. This function calculates the cost to transform all array elements to a target value. The cost is the sum of absolute differences between each element and the target, each weighted by its corresponding weight.

  • Establish the search range for the possible values the array can be equalized to using the minimum and maximum values in the array.

  • Implement a binary search within this range to find the value that results in the minimum cost:

    • Calculate the cost of changing all array elements to the middle of the current range (mid_point) and one above it (mid_point + 1).
    • Update the optimal cost with the minimum of these two costs.
    • Adjust the search range based on whether the cost decreases or increases when moving from mid_point to mid_point + 1. If the cost is lower at mid_point + 1, adjust the lower bound of the range; otherwise, adjust the upper bound to refine the search for minimal cost.
  • Finally, the minimized cost is returned from the function once the optimal middle point is determined.

This method effectively minimizes the computational complexity to O(log(range of values) * n) where n is the number of elements in the input array, making it efficient by utilizing a weighted binary search technique.

Comments

No comments yet.