|
| 1 | +/** |
| 2 | + * 1681. Minimum Incompatibility |
| 3 | + * https://leetcode.com/problems/minimum-incompatibility/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an integer array nums and an integer k. You are asked to distribute this array |
| 7 | + * into k subsets of equal size such that there are no two equal elements in the same subset. |
| 8 | + * |
| 9 | + * A subset's incompatibility is the difference between the maximum and minimum elements in that |
| 10 | + * array. |
| 11 | + * |
| 12 | + * Return the minimum possible sum of incompatibilities of the k subsets after distributing the |
| 13 | + * array optimally, or return -1 if it is not possible. |
| 14 | + * |
| 15 | + * A subset is a group integers that appear in the array with no particular order. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number[]} nums |
| 20 | + * @param {number} k |
| 21 | + * @return {number} |
| 22 | + */ |
| 23 | +var minimumIncompatibility = function(nums, k) { |
| 24 | + const n = nums.length; |
| 25 | + const subsetSize = n / k; |
| 26 | + const freq = new Array(n + 1).fill(0); |
| 27 | + for (const num of nums) { |
| 28 | + freq[num]++; |
| 29 | + if (freq[num] > k) return -1; |
| 30 | + } |
| 31 | + |
| 32 | + nums.sort((a, b) => a - b); |
| 33 | + const subsetValues = new Map(); |
| 34 | + |
| 35 | + computeSubsets(0, 0, 0, 0, 0, []); |
| 36 | + |
| 37 | + const dp = new Array(1 << n).fill(Infinity); |
| 38 | + dp[0] = 0; |
| 39 | + |
| 40 | + for (let mask = 0; mask < (1 << n); mask++) { |
| 41 | + if (dp[mask] === Infinity) continue; |
| 42 | + for (const [subsetMask, value] of subsetValues) { |
| 43 | + if ((mask & subsetMask) === 0) { |
| 44 | + const newMask = mask | subsetMask; |
| 45 | + dp[newMask] = Math.min(dp[newMask], dp[mask] + value); |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return dp[(1 << n) - 1] === Infinity ? -1 : dp[(1 << n) - 1]; |
| 51 | + |
| 52 | + function computeSubsets(mask, index, count, minVal, maxVal, selected) { |
| 53 | + if (count === subsetSize) { |
| 54 | + subsetValues.set(mask, maxVal - minVal); |
| 55 | + return; |
| 56 | + } |
| 57 | + if (index >= n || n - index < subsetSize - count) return; |
| 58 | + |
| 59 | + computeSubsets(mask, index + 1, count, minVal, maxVal, selected); |
| 60 | + if (!selected.includes(nums[index])) { |
| 61 | + computeSubsets(mask | (1 << index), index + 1, count + 1, |
| 62 | + count === 0 ? nums[index] : minVal, nums[index], [...selected, nums[index]]); |
| 63 | + } |
| 64 | + } |
| 65 | +}; |
0 commit comments