[LeetCode] Maximum Number of Achievable Transfer Requests

1601. Maximum Number of Achievable Transfer Requests

We have n buildings numbered from 0 to n - 1. Each building has a number of employees. It’s transfer season, and some employees want to change the building they reside in.

You are given an array requests where requests[i] = [fromi, toi] represents an employee’s request to transfer from building fromi to building toi.

All buildings are full, so a list of requests is achievable only if for each building, the net change in employee transfers is zero. This means the number of employees leaving is equal to the number of employees moving in. For example if n = 3 and two employees are leaving building 0, one is leaving building 1, and one is leaving building 2, there should be two employees moving to building 0, one employee moving to building 1, and one employee moving to building 2.

Return the maximum number of achievable requests.

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
class Solution {
int varify(int& mask, vector<vector<int>>& req, int& sz, int& n) {
vector<int> counter(n,0);
int bi = 0;
for(int i = 0; i < sz; i++) {
if(mask & (1<<i)) {
counter[req[i][0]]--;
counter[req[i][1]]++;
bi++;
}
}
for(auto c : counter) if(c) return 0;

return bi;
}
public:
int maximumRequests(int n, vector<vector<int>>& req) {
int res = 0, self = 0;
int sz = 0;

for(int i = 0; i < req.size(); i++) {
if(req[i][0] == req[i][1]) self++;
else {
req[sz++] = req[i];
}
}

res = self;
for(int mask = 0; mask < 1<<sz; mask++) {
res = max(res, varify(mask, req, sz, n) + self);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/25/PS/LeetCode/maximum-number-of-achievable-transfer-requests/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.