Problem Description
Given n buildings and an array of requests where each request represents a transfer from one building to another, determine the maximum number of requests that can be achieved such that for every building the net change (inflow minus outflow) is zero.
Key Insights
- The solution requires checking subsets of transfer requests.
- Brute-force subset enumeration is feasible given the maximum of 16 requests.
- For each subset, compute a net change array for all buildings.
- The subset is valid if the net change for every building is zero.
- Bit Manipulation is used to represent and iterate over subsets effectively.
Space and Time Complexity
Time Complexity: O(2^m * (n + m)), where m is the number of requests. Space Complexity: O(n) for the net change array.
Solution
We approach the problem by using bitmask enumeration to try every possible combination of requests. For each combination, we update an array representing the net change of employees in each building. A valid combination has all entries equal to zero. We maximize the count of requests in valid subsets. The key trick is to iterate over all 2^m combinations (where m is the number of requests) and use a bitmask to include/exclude each request. This approach works because m is small (up to 16), making the brute-force search efficient.