5
int minimumIncompatibility(vector<int> &nums, int k) {6
int i, n = nums.size(), subset_size = n / k;7
sort(nums.begin(), nums.end());9
// Pre-calculate the range (max - min) for each subset of nums10
// Note that there are (1 << n) subsets (i.e. 2 ^ n subsets) of an array of12
vector<int> range(1 << n, INF);14
// Each mask represents every possible subset of elements in num (so, "mask"15
// == "subset") Specifically, if the bit at position i of mask is set to 1,16
// then we include that number in the subset17
for (int mask = 1; mask < (1 << n); mask++) {18
int small = -1, big = -1;21
// Identify elements that belong to this subset, find the largest &22
// smallest, check for duplicates Recall that this array was sorted in the23
// beginning of the function24
for (i = 0; i < n && !dup; i++)25
if (mask & (1 << i)) {26
if (small == -1) small = nums[i];27
if (big == nums[i]) dup = true;31
// If no duplicates were found, then calculate and store the range for33
if (!dup) range[mask] = big - small;36
vector<int> dp(1 << n, INF);39
// Iterate over every mask (i.e. subset) and calculate its minimum sum40
for (int mask = 1; mask < (1 << n); mask++) {41
// Iterate over every submask for current mask42
for (int submask = mask; submask; submask = (submask - 1) & mask) {43
// Check that submask has the right number of elements44
if (__builtin_popcount(submask) == subset_size)45
// Note that mask = submask + (mask ^ submask)46
// ==> i.e., mask ^ submask = mask - submask47
// In other words, (mask ^ submask) represents those elements in mask48
// that are not in submask49
dp[mask] = min(dp[mask], range[submask] + dp[mask ^ submask]);52
// dp.back() == dp[(1 << n) - 1];53
return dp.back() >= INF ? -1 : dp.back();