- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 70 lines of Java from the credited upstream file 1681.java.
- The implementation visibly relies on sequence storage, cached states.
- 5 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int minimumIncompatibility(int[] nums, int k) {3 final int MAX_COMPATIBILITY = (16 - 1) * (16 / 2);4 final int n = nums.length;5 final int subsetSize = n / k;6 final int maxMask = 1 << n;7 final int[] incompatibilities = getIncompatibilities(nums, subsetSize);8 9 10 int[] dp = new int[maxMask];11 Arrays.fill(dp, MAX_COMPATIBILITY);12 dp[0] = 0;13 14 for (int mask = 1; mask < maxMask; ++mask) {15 16 if (Integer.bitCount(mask) % subsetSize != 0)17 continue;18 19 for (int submask = mask; submask > 0; submask = (submask - 1) & mask)20 if (incompatibilities[submask] != -1) 21 dp[mask] = Math.min(dp[mask], dp[mask - submask] + incompatibilities[submask]);22 }23 24 return dp[maxMask - 1] == MAX_COMPATIBILITY ? -1 : dp[maxMask - 1];25 }26 27 private static final int MAX_NUM = 16;28 29 30 31 32 33 34 private int[] getIncompatibilities(int[] nums, int subsetSize) {35 final int maxMask = 1 << nums.length;36 int[] incompatibilities = new int[maxMask];37 Arrays.fill(incompatibilities, -1);38 for (int mask = 0; mask < maxMask; ++mask)39 if (Integer.bitCount(mask) == subsetSize && isUnique(nums, mask, subsetSize))40 incompatibilities[mask] = getIncompatibility(nums, mask);41 return incompatibilities;42 }43 44 45 46 47 48 49 private boolean isUnique(int[] nums, int mask, int subsetSize) {50 int used = 0;51 for (int i = 0; i < nums.length; ++i)52 if ((mask >> i & 1) == 1)53 used |= 1 << nums[i];54 return Integer.bitCount(used) == subsetSize;55 }56 57 58 59 private int getIncompatibility(int[] nums, int mask) {60 int mn = MAX_NUM;61 int mx = 0;62 for (int i = 0; i < nums.length; ++i)63 if ((mask >> i & 1) == 1) {64 mx = Math.max(mx, nums[i]);65 mn = Math.min(mn, nums[i]);66 }67 return mx - mn;68 }69}70