LeetCode 2448: Minimum Cost to Make Array Equal Solution
Master LeetCode problem 2448 (Minimum Cost to Make Array Equal), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2448. Minimum Cost to Make Array Equal
Problem Explanation
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
- Calculate the median of the array.
- 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.
- 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.
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2448 (Minimum Cost to Make Array Equal)?
This page provides optimized solutions for LeetCode problem 2448 (Minimum Cost to Make Array Equal) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2448 (Minimum Cost to Make Array Equal)?
The time complexity for LeetCode 2448 (Minimum Cost to Make Array Equal) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2448 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2448 in Java, C++, or Python.