Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2448. Minimum Cost to Make Array Equal

Explanation

To minimize the total cost while making all elements of the array equal, we need to find the target value to which all elements will converge. This target value can be found by calculating the median of the array. Once we have the target value, we iterate through each element in the array and calculate the cost of moving that element to the target value. The total cost will be the sum of these individual costs.

Algorithm

  1. Calculate the median of the array.
  2. Iterate through each element in the array:
    • Calculate the cost of moving the element to the median (abs(target - element) * cost[i]).
    • Add this cost to the total cost.
  3. Return the total cost as the minimum cost to make the array equal.

Time Complexity

The time complexity of this algorithm is O(n) where n is the number of elements in the array.

Space Complexity

The space complexity of this algorithm is O(1) as we are using constant extra space.

class Solution {
    public int minCost(int[] nums, int[] cost) {
        int n = nums.length;
        long totalCost = 0;
        
        // Calculate the median
        Arrays.sort(nums);
        int target = nums[n / 2];
        
        // Calculate total cost
        for (int i = 0; i < n; i++) {
            totalCost += Math.abs(target - nums[i]) * cost[i];
        }
        
        return (int) totalCost;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.