[LeetCode] Minimum Numbers of Function Calls to Make Target Array

1558. Minimum Numbers of Function Calls to Make Target Array

You are given an integer array nums. You have an integer array arr of the same length with all values set to 0 initially. You also have the following modify function:

You want to use the modify function to covert arr to nums using the minimum number of calls.

Return the minimum number of function calls to make nums from arr.

The test cases are generated so that the answer fits in a 32-bit signed integer.

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
class Solution {
public:
int minOperations(vector<int>& A) {
unordered_map<int, int> freq;
for(auto& a : A) if(a) freq[a]++;
int res = 0;
while(!freq.empty()) {
unordered_map<int,int> nfreq;
int mask = INT_MAX;
for(auto& [u, v] : freq) {
if(u & 1) {mask = 0;}
else if(mask) {
int c = 0;
int v = u;
while(!(v & 1)) {
c++;
v>>=1;
}
mask = min(mask, c);
}
}
res += mask;
for(auto& [k,v] : freq) {
int kk = k;
if(mask) {
kk>>=mask;
} else if(kk & 1) {
kk -= 1;
res += v;
}
if(kk) nfreq[kk] += v;
}
swap(freq, nfreq);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/27/PS/LeetCode/minimum-numbers-of-function-calls-to-make-target-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.