C++ O(3^n) DP
\nclass Solution {\npublic:\n    int leftmostbit(int x){\n        return __builtin_ffs(x)-1;\n    }\n    int rightmostbit(int x){\n        return 31 - __builtin
```\nclass Solution {\npublic:\n    int leftmostbit(int x){\n        return __builtin_ffs(x)-1;\n    }\n    int rightmostbit(int x){\n        return 31 - __builtin_clz(x);\n    }\n    \n    int minCompat(int mask, vector<int>& nums){\n        int rsb = rightmostbit(mask);\n        int lsb = leftmostbit(mask);\n        int prev = lsb;\n        for(int i=lsb+1; i<=rsb; i++){\n            if(mask&(1<<i)){\n                if(nums[prev] == nums[i])\n                    return INT_MAX;\n                prev = i;\n            }\n        }\n        return  nums[rsb] - nums[lsb];\n    }\n    \n    const int N = 16+1;\n    int minimumIncompatibility(vector<int>& nums, int k) {\n\n        int n = nums.size();\n        \n        if(n%k!=0)\n            return -1;\n        int np = n/k;\n        vector<int>freq(N);\n        for(auto& x:nums){\n            freq[x]++;\n            if(freq[x]>k)\n                return -1;\n        }\n        \n        int fmask = (1<<n)-1;\n        \n        sort(nums.begin(), nums.end());\n      \n        vector<long>dp(fmask+1,INT_MAX);\n        dp[0] = 0;\n        for(int mask=1; mask<fmask+1; mask++){\n            if(__builtin_popcount(mask)%np != 0)\n                continue;\n            for(int submask = mask; submask>0; submask = (submask-1)&mask){\n                if(__builtin_popcount(submask) != np)\n                    continue;\n                dp[mask] = min(dp[mask], dp[mask-submask] + minCompat(submask, nums));\n            }\n        }\n        \n        return dp[fmask];\n    }\n};\n```
['Dynamic Programming', 'C', 'Bitmask']