LeetCode 2541: Minimum Operations to Make Array Equal II

ArrayMathGreedy

Problem Description

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:

  1. Sort both arrays.
  2. Calculate the difference between corresponding elements and store them in a separate array.
  3. Check if the sum of differences is divisible by k. If not, return -1.
  4. Calculate the median of the differences.
  5. 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.

Solutions

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;
    }
}

Loading editor...