Maximum Number of Achievable Transfer Requests — LeetCode 1601 Python Solution

HardBit ManipulationArrayBacktrackingEnumeration
Problem
#1601
Reading time
3 min

The problem

We have n buildings numbered from 0 to n - 1. Each building has a number of employees.

Example

Input
n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]]
Output
5

Python solution

Python
class Solution:
    def maximumRequests(self, n: int, requests: List[List[int]]) -> int:
        def check(mask: int) -> bool:
            cnt = [0] * n
            for i, (f, t) in enumerate(requests):
                if mask >> i & 1:
                    cnt[f] -= 1
                    cnt[t] += 1
            return all(v == 0 for v in cnt)

        ans = 0
        for mask in range(1 << len(requests)):
            cnt = mask.bit_count()
            if ans < cnt and check(mask):
                ans = cnt
        return ans

Complexity

MeasureComplexity
TimeO(2^m \times (m + n))
SpaceO(n), where m and n are the lengths of the room change request list and the number of rooms, respectively auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 1601. Maximum Number of Achievable Transfer Requests is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1601. Maximum Number of Achievable Transfer Requests?
LeetCode 1601. Maximum Number of Achievable Transfer Requests is rated Hard on LeetCode.
What is the time complexity of LeetCode 1601. Maximum Number of Achievable Transfer Requests?
The Python solution on this page runs in O(2^m \times (m + n)).
What is the space complexity of LeetCode 1601. Maximum Number of Achievable Transfer Requests?
The Python solution on this page uses O(n), where m and n are the lengths of the room change request list and the number of rooms, respectively auxiliary space.
What topics does LeetCode 1601. Maximum Number of Achievable Transfer Requests cover?
LeetCode 1601. Maximum Number of Achievable Transfer Requests is tagged Bit Manipulation, Array, Backtracking and Enumeration on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview