[LeetCode] Minimum Number of Operations to Make Arrays Similar

2449. Minimum Number of Operations to Make Arrays Similar

You are given two positive integer arrays nums and target, of the same length.

In one operation, you can choose any two distinct indices i and j where 0 <= i, j < nums.length and:

  • set nums[i] = nums[i] + 2 and
  • set nums[j] = nums[j] - 2.

Two arrays are considered to be similar if the frequency of each element is the same.

Return the minimum number of operations required to make nums similar to target. The test cases are generated such that nums can always be similar to target.

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
class Solution {
public:
long long makeSimilar(vector<int>& A, vector<int>& B) {
vector<int> oa, ea, ob, eb;
for(int i = 0; i < A.size(); i++) {
if(A[i] % 2) oa.push_back(A[i]);
else ea.push_back(A[i]);

if(B[i] % 2) ob.push_back(B[i]);
else eb.push_back(B[i]);
}
sort(begin(oa), end(oa));
sort(begin(ea), end(ea));
sort(begin(ob), end(ob));
sort(begin(eb), end(eb));
long long res = 0;
for(int i = 0; i < oa.size(); i++) {
if(oa[i] < ob[i]) res += (ob[i] - oa[i]) / 2;
}
for(int i = 0; i < ea.size(); i++) {
if(ea[i] < eb[i]) res += (eb[i] - ea[i]) / 2;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/19/PS/LeetCode/minimum-number-of-operations-to-make-arrays-similar/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.