-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
maximum-total-reward-using-operations-i.py
68 lines (61 loc) · 1.75 KB
/
maximum-total-reward-using-operations-i.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# Time: O(nlogn + r^2), r = max(rewardValues)
# Space: O(r)
# sort, dp, bitset
class Solution(object):
def maxTotalReward(self, rewardValues):
"""
:type rewardValues: List[int]
:rtype: int
"""
mx = max(rewardValues)
dp = 1
mask = (1<<mx)-1
for v in sorted(set(rewardValues)):
x = dp&((1<<v)-1)
dp |= (x<<v)&mask
return mx+(dp.bit_length()-1)
# Time: O(nlogn + r^2), r = max(rewardValues)
# Space: O(r)
# sort, dp, bitset
class Solution2(object):
def maxTotalReward(self, rewardValues):
"""
:type rewardValues: List[int]
:rtype: int
"""
dp = 1
for v in sorted(set(rewardValues)):
x = dp&((1<<v)-1)
dp |= x<<v
return dp.bit_length()-1
# Time: O(nlogn + r^2), r = max(rewardValues)
# Space: O(r)
# sort, dp
class Solution3(object):
def maxTotalReward(self, rewardValues):
"""
:type rewardValues: List[int]
:rtype: int
"""
mx = max(rewardValues)
dp = [False]*((mx-1)+1)
dp[0] = True
for v in sorted(set(rewardValues)):
for x in xrange(min(v, mx-v)):
dp[x+v] |= dp[x]
return mx+next(x for x in reversed(xrange(len(dp))) if dp[x])
# Time: O(nlogn + r^2), r = max(rewardValues)
# Space: O(r)
# sort, dp
class Solution4(object):
def maxTotalReward(self, rewardValues):
"""
:type rewardValues: List[int]
:rtype: int
"""
dp = [False]*((max(rewardValues)*2-1)+1)
dp[0] = True
for v in sorted(set(rewardValues)):
for x in xrange(v):
dp[x+v] |= dp[x]
return next(x for x in reversed(xrange(len(dp))) if dp[x])