Python3 || ~100ms, Fast O(n^2*2^n) DP w/ comments
Approach\n Describe your approach to solving the problem. \n- Preprocessing:\n    - Sort the nums and handle the impossible and trivial cases.\n    - nxt: nxt[i
# Approach\n<!-- Describe your approach to solving the problem. -->\n- Preprocessing:\n    - Sort the `nums` and handle the impossible and trivial cases.\n    - `nxt`: `nxt[i]` points to the next number in `nums`, so that we can skip the duplicates.\n\n- DP states:\n  - `bitMap`:   A bit map tracking which numbers have been used.\n  - `i`:        Index of the current number in `nums`.\n  - `sz`:       Size of the current group.\n  - A pruning trick: We always take the smallest available number as the beginning of a new group.\n# Complexity\n- Time complexity: $O(2^n \\cdot n \\cdot n / k)$ ~ $O(n^2 \\cdot 2^n)$\n\n- Space complexity: $O(2^n \\cdot n \\cdot n/k)$, it can be optimized to $O(2^n \\cdot n)$.\n\n# Code\n```python\nclass Solution:\n    def minimumIncompatibility(self, nums: List[int], k: int) -> int:\n        \n        nums.sort()\n        n = len(nums)\n\n        # Impossible to form k groups \n        if max(Counter(nums).values()) > k:     return -1\n\n        # Trivial cases\n        if k == n:      return 0\n        if k == 1:      return nums[-1] - nums[0]\n        \n        # `nxt[i]` points to the next number larger than `nums[i]`\n        nxt, cur, ptr = [0]*n, nums[-1], n\n        for i in range(n-1, -1, -1):\n            if nums[i] != cur:\n                cur, ptr = nums[i], i+1\n            nxt[i] = ptr\n        \n        # Group size and the end state\n        gs, end = n//k-1, (1<<n)-1\n\n        @lru_cache(None)\n        def dp(bitMap: int, i: int, sz: int) -> int:\n\n            # End state\n            if bitMap == end:   return 0\n\n            # Not enough elements in the current group\n            if i == n:          return inf\n\n            # The current num/bit has been used\n            if bitMap&1<<i:     return dp(bitMap, i+1, sz)\n\n            # Beginning of the current group, take the smallest available number\n            if sz == 0:         return dp(bitMap|1<<i, nxt[i], 1) - nums[i]\n\n            # Middle of the current group\n            if sz < gs:         return min(dp(bitMap|1<<i, nxt[i], sz+1)  ,  dp(bitMap, nxt[i], sz))\n\n            # End of the current group, start a new group\n            else:               return min(dp(bitMap|1<<i, 0, 0) + nums[i],  dp(bitMap, nxt[i], sz))\n\n        return dp(0,0,0)\n```
['Dynamic Programming', 'Bitmask', 'Python3']