LeetCode-in-Java

3868. Minimum Cost to Equalize Arrays Using Swaps

Medium

You are given two integer arrays nums1 and nums2 of size n.

You can perform the following two operations any number of times on these two arrays:

Return an integer denoting the minimum cost to make nums1 and nums2 identical. If this is not possible, return -1.

Example 1:

Input: nums1 = [10,20], nums2 = [20,10]

Output: 0

Explanation:

Example 2:

Input: nums1 = [10,10], nums2 = [20,20]

Output: 1

Explanation:

Example 3:

Input: nums1 = [10,20], nums2 = [30,40]

Output: -1

Explanation:

It is impossible to make the two arrays identical. Therefore, the answer is -1.

Constraints:

Solution

import java.util.HashMap;
import java.util.Map;

public class Solution {
    public int minCost(int[] a, int[] b) {
        Map<Integer, Integer> m = new HashMap<>();
        for (int x : a) {
            m.merge(x, 1, Integer::sum);
        }
        for (int x : b) {
            m.merge(x, -1, Integer::sum);
        }
        int res = 0;
        for (int v : m.values()) {
            if (v % 2 != 0) {
                return -1;
            }
            if (v > 0) {
                res += v / 2;
            }
        }
        return res;
    }
}