File tree 1 file changed +47
-0
lines changed
1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ import kotlin.math.abs
2
+
3
+ class Solution {
4
+ private var min = Int .MAX_VALUE
5
+ private var bucketSize = 0
6
+
7
+ fun minimumIncompatibility (nums : IntArray , k : Int ): Int {
8
+ val n = nums.size
9
+ bucketSize = n / k
10
+ val sets: MutableList <MutableSet <Int >> = ArrayList ()
11
+ for (i in 0 until k) {
12
+ sets.add(HashSet ())
13
+ }
14
+ backtrack(nums, 0 , sets, 0 )
15
+ return if (min == Int .MAX_VALUE ) - 1 else min
16
+ }
17
+
18
+ private fun backtrack (nums : IntArray , idx : Int , sets : List <MutableSet <Int >>, acc : Int ) {
19
+ var acc = acc
20
+ if (idx >= nums.size) {
21
+ min = min.coerceAtMost(acc)
22
+ return
23
+ }
24
+ val visited: MutableSet <Set <Int >> = HashSet ()
25
+ for (set in sets) {
26
+ if (set.contains(nums[idx]) || set.size == bucketSize || visited.contains(set)) continue
27
+ val impact = computeImpact(set, nums[idx])
28
+ acc + = impact
29
+ if (acc < min) {
30
+ set.add(nums[idx])
31
+ backtrack(nums, idx + 1 , sets, acc)
32
+ set.remove(nums[idx])
33
+ }
34
+ acc - = impact
35
+ visited.add(set)
36
+ }
37
+ }
38
+
39
+ private fun computeImpact (set : Set <Int >, num : Int ): Int {
40
+ if (set.isEmpty()) return 0
41
+ if (set.size == 1 ) return abs(num - set.first())
42
+ val lo = set.min()!!
43
+ val hi = set.max()!!
44
+ if (num < lo) return lo - num
45
+ return if (num > hi) num - hi else 0
46
+ }
47
+ }
You can’t perform that action at this time.
0 commit comments