forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-number-of-achievable-transfer-requests.py
47 lines (41 loc) · 1.35 KB
/
maximum-number-of-achievable-transfer-requests.py
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
38
39
40
41
42
43
44
45
46
47
# Time: O((n + r) * 2^r)
# Space: O(n + r)
import itertools
# early return solution
class Solution(object):
def maximumRequests(self, n, requests):
"""
:type n: int
:type requests: List[List[int]]
:rtype: int
"""
for k in reversed(xrange(1, len(requests)+1)):
for c in itertools.combinations(xrange(len(requests)), k):
change = [0]*n
for i in c:
change[requests[i][0]] -= 1
change[requests[i][1]] += 1
if all(c == 0 for c in change):
return k # early return
return 0
# Time: O((n + r) * 2^r)
# Space: O(n + r)
# full search solution (much slower)
class Solution2(object):
def maximumRequests(self, n, requests):
"""
:type n: int
:type requests: List[List[int]]
:rtype: int
"""
def evaluate(n, requests, mask):
change = [0]*n
base, count = 1, 0
for i in xrange(len(requests)):
if base & mask:
change[requests[i][0]] -= 1
change[requests[i][1]] += 1
count += 1
base <<= 1
return count if all(c == 0 for c in change) else 0
return max(evaluate(n, requests, i) for i in xrange(1 << len(requests)))