-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
32 lines (31 loc) · 1020 Bytes
/
Solution.java
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
class Solution {
public int maxScore(int[] nums) {
int m = nums.length;
int[][] g = new int[m][m];
for (int i = 0; i < m; ++i) {
for (int j = i + 1; j < m; ++j) {
g[i][j] = gcd(nums[i], nums[j]);
}
}
int[] f = new int[1 << m];
for (int k = 0; k < 1 << m; ++k) {
int cnt = Integer.bitCount(k);
if (cnt % 2 == 0) {
for (int i = 0; i < m; ++i) {
if (((k >> i) & 1) == 1) {
for (int j = i + 1; j < m; ++j) {
if (((k >> j) & 1) == 1) {
f[k] = Math.max(
f[k], f[k ^ (1 << i) ^ (1 << j)] + cnt / 2 * g[i][j]);
}
}
}
}
}
}
return f[(1 << m) - 1];
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}