- 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 Python from the credited upstream file 1681.py.
- The implementation visibly relies on sequence storage, cached states.
- No explicit 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 def __init__(self):3 self.MAX_NUM = 164 5 def minimumIncompatibility(self, nums: list[int], k: int) -> int:6 MAX_COMPATIBILITY = (16 - 1) * (16 2)7 n = len(nums)8 subsetSize = n k9 maxMask = 1 << n10 incompatibilities = self._getIncompatibilities(nums, subsetSize)11 12 13 14 dp = [MAX_COMPATIBILITY] * maxMask15 dp[0] = 016 17 for mask in range(1, maxMask):18 19 if mask.bit_count() % subsetSize != 0:20 continue21 22 submask = mask23 while submask > 0:24 if incompatibilities[submask] != -1: 25 dp[mask] = min(dp[mask], dp[mask - submask] +26 incompatibilities[submask])27 submask = (submask - 1) & mask28 29 return dp[-1] if dp[-1] != MAX_COMPATIBILITY else -130 31 def _getIncompatibilities(32 self,33 nums: list[int],34 subsetSize: int,35 ) -> list[int]:36 """37 Returns an incompatibilities array where38 * incompatibilities[i] := the incompatibility of the subset of numbers39 represented by the bitmask i40 * incompatibilities[i] := -1 if the number of 1s in the bitmask i is not41 `subsetSize`42 """43 maxMask = 1 << len(nums)44 incompatibilities = [-1] * maxMask45 for mask in range(maxMask):46 if mask.bit_count() == subsetSize and self._isUnique(nums, mask, subsetSize):47 incompatibilities[mask] = self._getIncompatibility(nums, mask)48 return incompatibilities49 50 def _isUnique(self, nums: list[int], mask: int, subsetSize: int) -> bool:51 """Returns True if the numbers selected by `mask` are unique."""52 used = 053 for i, num in enumerate(nums):54 if mask >> i & 1:55 used |= 1 << num56 return used.bit_count() == subsetSize57 58 def _getIncompatibility(self, nums: list[int], mask: int) -> int:59 """60 Returns the incompatibility of the selected numbers represented by the61 `mask`.62 """63 mn = self.MAX_NUM64 mx = 065 for i, num in enumerate(nums):66 if mask >> i & 1:67 mx = max(mx, num)68 mn = min(mn, num)69 return mx - mn70