Skip to content

Commit 4ea6dd6

Browse files
authored
Create maximum-number-of-achievable-transfer-requests.py
1 parent c753feb commit 4ea6dd6

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Time: O((n + r) * 2^r)
2+
# Space: O(n + r)
3+
4+
import itertools
5+
6+
7+
# early return solution
8+
class Solution(object):
9+
def maximumRequests(self, n, requests):
10+
"""
11+
:type n: int
12+
:type requests: List[List[int]]
13+
:rtype: int
14+
"""
15+
for k in reversed(xrange(1, len(requests)+1)):
16+
for c in itertools.combinations(xrange(len(requests)), k):
17+
change = [0]*n
18+
for i in c:
19+
change[requests[i][0]] -= 1
20+
change[requests[i][1]] += 1
21+
if all(c == 0 for c in change):
22+
return k # early return
23+
return 0
24+
25+
26+
# Time: O((n + r) * 2^r)
27+
# Space: O(n + r)
28+
# full search solution (much slower)
29+
class Solution(object):
30+
def maximumRequests(self, n, requests):
31+
"""
32+
:type n: int
33+
:type requests: List[List[int]]
34+
:rtype: int
35+
"""
36+
def evaluate(n, requests, mask):
37+
change = [0]*n
38+
base, count = 1, 0
39+
for i in xrange(len(requests)):
40+
if base & mask:
41+
change[requests[i][0]] -= 1
42+
change[requests[i][1]] += 1
43+
count += 1
44+
base <<= 1
45+
return count if all(c == 0 for c in change) else 0
46+
47+
return max(evaluate(n, requests, i) for i in xrange(1 << len(requests)))

0 commit comments

Comments
 (0)