Java with DP and backtracking
\nclass Solution {\n    int MAX=256;\n    public int minimumIncompatibility(int[] nums, int k) {\n        if(k==nums.length) return 0;\n        var cnts=new cha
```\nclass Solution {\n    int MAX=256;\n    public int minimumIncompatibility(int[] nums, int k) {\n        if(k==nums.length) return 0;\n        var cnts=new char[16];\n        Arrays.fill(cnts,\'0\');\n        for(var num:nums) {\n            cnts[num-1]=(char)(cnts[num-1]+1);\n            if(cnts[num-1]-\'0\'>k) return -1;\n        }\n        // each group has n nums\n        var n=nums.length/k;\n        return dfs(cnts,n,k,new HashMap<String,Integer>());\n    }\n    \n    int dfs(char[] cnts,int n,int k,Map<String,Integer> dp) {\n        if(k==0) return 0;\n        var key=new String(cnts);\n        var cnt=dp.get(key);\n        if(cnt==null) {\n            cnt=helper(cnts,n,k,dp,0,0,new int[n]);\n            dp.put(key,cnt);\n        }\n        return cnt;\n    }\n    \n    int helper(char[] cnts,int n,int k,Map<String,Integer> dp,int idx,int cnt,int[] dest) {\n        // already get n numbers\n        if(n==cnt) return dest[n-1]-dest[0]+dfs(cnts,n,k-1,dp);\n        // ran out of number\n        if(idx==cnts.length) return MAX;\n        //skip idx\n        var res=helper(cnts,n,k,dp,idx+1,cnt,dest);\n        if(cnts[idx]>\'0\') {\n            // backtracking\n            cnts[idx]=(char)(cnts[idx]-1);\n            dest[cnt]=idx;\n            res=Math.min(res,helper(cnts,n,k,dp,idx+1,cnt+1,dest));\n            cnts[idx]=(char)(cnts[idx]+1);\n        }\n        return res;\n    }\n}\n```
[]