Skip to content

Commit 6fc5dad

Browse files
authored
Update 1681-minimum-incompatibility.js
1 parent f2c8e66 commit 6fc5dad

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

1681-minimum-incompatibility.js

+56
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,59 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} k
4+
* @return {number}
5+
*/
6+
var minimumIncompatibility = function (nums, k) {
7+
if (k === nums.length) {
8+
return 0
9+
}
10+
const counts = Array(nums.length + 1).fill(0)
11+
for (let num of nums) {
12+
counts[num]++
13+
if (counts[num] > k) {
14+
return -1
15+
}
16+
}
17+
const size = nums.length / k
18+
let ans = Number.MAX_VALUE
19+
const backtracking = (groupIdx, index, sum, lowIndex, curIndex) => {
20+
if (index === size) {
21+
sum += curIndex - lowIndex
22+
if (sum > ans) {
23+
return
24+
}
25+
if (groupIdx === k - 1) {
26+
ans = sum
27+
return
28+
} else {
29+
groupIdx++
30+
index = 0
31+
}
32+
}
33+
if (index === 0) {
34+
for (let i = 0; i < counts.length; i++) {
35+
if (counts[i]) {
36+
counts[i]--
37+
backtracking(groupIdx, index + 1, sum, i, i)
38+
counts[i]++
39+
}
40+
}
41+
} else {
42+
for (let i = curIndex + 1; i < counts.length; i++) {
43+
if (counts[i]) {
44+
counts[i]--
45+
backtracking(groupIdx, index + 1, sum, lowIndex, i)
46+
counts[i]++
47+
}
48+
}
49+
}
50+
}
51+
backtracking(0, 0, 0, 0, 0)
52+
return ans
53+
}
54+
55+
// another
56+
157
/**
258
* @param {number[]} nums
359
* @param {number} k

0 commit comments

Comments
 (0)