Skip to content

Commit 89ea113

Browse files
authored
Update 1681-minimum-incompatibility.js
1 parent fd314ca commit 89ea113

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

1681-minimum-incompatibility.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,49 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} k
4+
* @return {number}
5+
*/
6+
const minimumIncompatibility = function(nums, k) {
7+
const n = nums.length
8+
const size = n / k
9+
const mod = 1e9 + 7
10+
if(size === 1) return 0
11+
const limit = 1 << n
12+
const dp = Array.from({ length: limit }, () => Array(16).fill(Infinity))
13+
for(let i = 0; i < n; i++) dp[1 << i][i] = 0
14+
15+
for(let mask = 0; mask < limit; mask++) {
16+
for(let i = 0; i < n; i++) {
17+
if((mask & (1 << i)) === 0) continue
18+
for(let j = 0; j < n; j++) {
19+
if((mask & (1 << j))) continue
20+
const newMask = mask | (1 << j)
21+
if(bitCnt(mask) % size === 0) {
22+
dp[newMask][j] = Math.min(dp[newMask][j], dp[mask][i])
23+
} else if(nums[j] > nums[i]) {
24+
dp[newMask][j] = Math.min(dp[newMask][j], dp[mask][i] + nums[j] - nums[i])
25+
}
26+
}
27+
}
28+
}
29+
30+
const candidate = Math.min(...dp.at(-1))
31+
32+
return candidate === Infinity ? -1 : candidate
33+
34+
function bitCnt(num) {
35+
let res = 0
36+
while(num) {
37+
if(num & 1) res++
38+
num = num >> 1
39+
}
40+
41+
return res
42+
}
43+
};
44+
45+
// another
46+
147
/**
248
* @param {number[]} nums
349
* @param {number} k

0 commit comments

Comments
 (0)