|
| 1 | +/** |
| 2 | + * @param {number[]} nums |
| 3 | + * @param {number} k |
| 4 | + * @return {number} |
| 5 | + */ |
| 6 | +const minimumIncompatibility = function (nums, k) { |
| 7 | + if (nums.length === k) return 0 |
| 8 | + const maxInBucket = nums.length / k |
| 9 | + const freqCount = {} |
| 10 | + for (const n of nums) { |
| 11 | + if (freqCount[n]) { |
| 12 | + if (freqCount[n] === k) { |
| 13 | + return -1 |
| 14 | + } else { |
| 15 | + freqCount[n]++ |
| 16 | + } |
| 17 | + } else { |
| 18 | + freqCount[n] = 1 |
| 19 | + } |
| 20 | + } |
| 21 | + const cache = {} |
| 22 | + const allIndiciesUsedMask = 2 ** nums.length - 1 |
| 23 | + const dfs = (usedIndicesBitMask) => { |
| 24 | + if (usedIndicesBitMask === allIndiciesUsedMask) { |
| 25 | + return 0 |
| 26 | + } |
| 27 | + if (cache[usedIndicesBitMask]) { |
| 28 | + return cache[usedIndicesBitMask] |
| 29 | + } |
| 30 | + const valsToIndices = {} |
| 31 | + for (let i = 0; i < nums.length; i++) { |
| 32 | + const indexMask = 1 << i |
| 33 | + if (usedIndicesBitMask & indexMask) continue |
| 34 | + const value = nums[i] |
| 35 | + if (!valsToIndices.hasOwnProperty(value)) { |
| 36 | + valsToIndices[value] = i |
| 37 | + } |
| 38 | + } |
| 39 | + const indicesAvailable = Object.values(valsToIndices) |
| 40 | + let minIncompatibilityCost = Infinity |
| 41 | + const combinations = createCombinations(indicesAvailable, maxInBucket) |
| 42 | + for (const indices of combinations) { |
| 43 | + let nextMask = usedIndicesBitMask |
| 44 | + let minVal = Infinity |
| 45 | + let maxVal = -Infinity |
| 46 | + for (const index of indices) { |
| 47 | + minVal = Math.min(minVal, nums[index]) |
| 48 | + maxVal = Math.max(maxVal, nums[index]) |
| 49 | + nextMask = nextMask | (1 << index) |
| 50 | + } |
| 51 | + const incompatibilityCost = maxVal - minVal |
| 52 | + minIncompatibilityCost = Math.min( |
| 53 | + minIncompatibilityCost, |
| 54 | + dfs(nextMask) + incompatibilityCost |
| 55 | + ) |
| 56 | + } |
| 57 | + return (cache[usedIndicesBitMask] = minIncompatibilityCost) |
| 58 | + } |
| 59 | + return dfs(0) |
| 60 | +} |
| 61 | + |
| 62 | +function createCombinations(indices, len) { |
| 63 | + const combinations = [] |
| 64 | + if (indices.length < len) { |
| 65 | + return combinations |
| 66 | + } |
| 67 | + const stack = [[[], 0]] |
| 68 | + while (stack.length > 0) { |
| 69 | + let [combi, i] = stack.pop() |
| 70 | + for (; i < indices.length; i++) { |
| 71 | + const combination = [...combi, indices[i]] |
| 72 | + if (combination.length === len) { |
| 73 | + combinations.push(combination) |
| 74 | + } else { |
| 75 | + stack.push([combination, i + 1]) |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | + return combinations |
| 80 | +} |
0 commit comments