[LeetCode] Minimum Total Cost to Make Arrays Unequal

2499. Minimum Total Cost to Make Arrays Unequal

You are given two 0-indexed integer arrays nums1 and nums2, of equal length n.

In one operation, you can swap the values of any two indices of nums1. The cost of this operation is the sum of the indices.

Find the minimum total cost of performing the given operation any number of times such that nums1[i] != nums2[i] for all 0 <= i <= n - 1 after performing all the operations.

Return the minimum total cost such that nums1 and nums2 satisfy the above condition. In case it is not possible, return -1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
bool check(vector<int>& A, vector<int>& B) {
int n = A.size();
unordered_map<int, int> freq;
for(auto& a : A) if(++freq[a] > n) return false;
for(auto& b : B) if(++freq[b] > n) return false;
return true;
}
public:
long long minimumTotalCost(vector<int>& A, vector<int>& B) {
if(!check(A,B)) return -1;
unordered_map<int, vector<int>> freq;
int cnt = 0;
long long res = 0;
for(int i = A.size() - 1; i >= 0; i--) {
if(A[i] != B[i]) continue;
res += i;
cnt += 1;
freq[A[i]].push_back(i);
}
if(cnt % 2 == 0) return res;
if(freq.size() >= 3) return res;
priority_queue<pair<int,int>> q;
for(auto& [k,v] : freq) q.push({v.size(), k});
while(q.size() > 1) {
int a = q.top().second; q.pop();
int b = q.top().second; q.pop();
auto& v1 = freq[a];
auto& v2 = freq[b];
while(v1.size() and v2.size()) {
swap(A[v1.back()], A[v2.back()]);
v1.pop_back();
v2.pop_back();
}
if(v1.size()) q.push({v1.size(), a});
if(v2.size()) q.push({v2.size(), b});
}
if(q.size()) {
int key = q.top().second; q.pop();
auto& vec = freq[key];
for(int i = 0; i < A.size() and vec.size(); i++) {
if(A[i] == B[i]) continue;
if(A[i] == key or B[i] == key) continue;
swap(A[vec.back()], A[i]);
res += i;
vec.pop_back();
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/12/11/PS/LeetCode/minimum-total-cost-to-make-arrays-unequal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.