LeetCode 2541: Minimum Operations to Make Array Equal II Solution
Master LeetCode problem 2541 (Minimum Operations to Make Array Equal II), a medium 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.
Problem Explanation
Explanation
To solve this problem, we need to determine the minimum number of operations required to transform nums1 into nums2. The idea is to sort both arrays and then calculate the difference between the corresponding elements. If the sum of differences is not divisible by k, we return -1 as it is impossible to make the arrays equal. Otherwise, we calculate the median of the differences and find the number of operations required to make the elements equal to the median.
The steps are as follows:
- Sort both arrays.
- Calculate the difference between corresponding elements and store them in a separate array.
- Check if the sum of differences is divisible by
k. If not, return-1. - Calculate the median of the differences.
- Calculate the number of operations required to make elements equal to the median.
The time complexity of this solution is O(n log n) due to sorting, and the space complexity is O(n) to store the differences.
Solution Code
import java.util.Arrays;
class Solution {
public int minOperations(int[] nums1, int[] nums2, int k) {
int n = nums1.length;
int[] diff = new int[n];
for (int i = 0; i < n; i++) {
diff[i] = nums2[i] - nums1[i];
}
Arrays.sort(diff);
int sum = 0;
for (int d : diff) {
sum += d;
}
if (sum % k != 0) {
return -1;
}
int target = 0;
if (sum > 0) {
target = diff[n/2];
} else {
target = diff[n/2 - 1];
}
int operations = 0;
for (int d : diff) {
operations += Math.abs(d - target) / k;
}
return operations;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2541 (Minimum Operations to Make Array Equal II)?
This page provides optimized solutions for LeetCode problem 2541 (Minimum Operations to Make Array Equal II) 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 2541 (Minimum Operations to Make Array Equal II)?
The time complexity for LeetCode 2541 (Minimum Operations to Make Array Equal II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2541 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2541 in Java, C++, or Python.