-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy path1799-maximize-score-after-n-operations.js
73 lines (66 loc) · 1.61 KB
/
1799-maximize-score-after-n-operations.js
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
69
70
71
72
73
/**
* @param {number[]} nums
* @return {number}
*/
const maxScore = function (nums) {
const len = nums.length
const n = len / 2
const allMask = 2 ** 14 - 1
const memo = Array.from({ length: n + 1 }, () => Array())
return helper(1, 0)
function helper(op, mask) {
if(op > n) return 0
if(memo[op][mask]) return memo[op][mask]
let res = 0
for(let i = 0; i < len; i++) {
const a = nums[i]
for(let j = i + 1; j < len; j++) {
const b = nums[j]
const newMask = (1 << i) + (1 << j)
if((mask & newMask) === 0) {
res = Math.max(res, op * gcd(a, b) + helper(op + 1, mask | newMask))
}
}
}
// console.log(res)
memo[op][mask] = res
return memo[op][mask]
}
}
function gcd(a, b) {
return b === 0 ? a : gcd(b, a % b)
}
// another
/**
* @param {number[]} nums
* @return {number}
*/
const maxScore = function (nums) {
const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b))
const n = nums.length / 2
const memo = {}
const traverse = (op, mask) => {
if (op > n) {
return 0
}
const idx = op * 100000 + mask
if (memo[idx] === undefined) {
let res = 0
for (let i = 0; i < 2 * n - 1; i++) {
if (mask & (1 << i)) continue
for (let j = i + 1; j < 2 * n; j++) {
if (mask & (1 << j)) continue
const newMask = mask | (1 << i) | (1 << j)
res = Math.max(
res,
traverse(op + 1, newMask) + op * gcd(nums[i], nums[j])
)
}
}
memo[idx] = res
}
return memo[idx]
}
const res = traverse(1, 0)
return res
}