forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximize-score-after-n-operations.py
More file actions
38 lines (33 loc) · 950 Bytes
/
maximize-score-after-n-operations.py
File metadata and controls
38 lines (33 loc) · 950 Bytes
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
# Time: O(n^2 * 2^n)
# Space: O(2^n)
import itertools
from fractions import gcd
class Solution(object):
def maxScore(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def popcount(n):
count = 0
while n:
n &= n-1
count += 1
return count
def bits(mask):
result = []
i = 0
while mask:
if mask&1:
result.append(i)
i += 1
mask >>= 1
return result
dp = [0]*(2**len(nums))
for mask in xrange(3, len(dp)):
cnt = popcount(mask)
if cnt%2:
continue
for i, j in itertools.combinations(bits(mask), 2): # Time: O(n^2)
dp[mask] = max(dp[mask], cnt//2*gcd(nums[i], nums[j]) + dp[mask^(1<<i)^(1<<j)])
return dp[-1]