- 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
- 72 lines of C++ from the credited upstream file 1681.cpp.
- 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:3 int minimumIncompatibility(vector<int>& nums, int k) {4 constexpr int kMaxCompatibility = (16 - 1) * (16 / 2);5 const int n = nums.size();6 const int subsetSize = n / k;7 const int maxMask = 1 << n;8 const vector<int> incompatibilities =9 getIncompatibilities(nums, subsetSize);10 11 12 vector<int> dp(maxMask, kMaxCompatibility);13 dp[0] = 0;14 15 for (unsigned mask = 1; mask < maxMask; ++mask) {16 17 if (popcount(mask) % subsetSize != 0)18 continue;19 20 for (int submask = mask; submask > 0; submask = (submask - 1) & mask)21 if (incompatibilities[submask] != -1) 22 dp[mask] =23 min(dp[mask], dp[mask - submask] + incompatibilities[submask]);24 }25 26 return dp.back() == kMaxCompatibility ? -1 : dp.back();27 }28 29 private:30 static constexpr int kMaxNum = 16;31 32 33 34 35 36 37 vector<int> getIncompatibilities(const vector<int>& nums, int subsetSize) {38 const int maxMask = 1 << nums.size();39 vector<int> incompatibilities(maxMask, -1);40 for (unsigned mask = 0; mask < maxMask; ++mask)41 if (popcount(mask) == subsetSize && isUnique(nums, mask, subsetSize))42 incompatibilities[mask] = getIncompatibility(nums, mask);43 return incompatibilities;44 }45 46 47 48 49 50 51 bool isUnique(const vector<int>& nums, int mask, int subsetSize) {52 unsigned used = 0;53 for (int i = 0; i < nums.size(); ++i)54 if (mask >> i & 1)55 used |= 1 << nums[i];56 return popcount(used) == subsetSize;57 }58 59 60 61 int getIncompatibility(const vector<int>& nums, int mask) {62 int mn = kMaxNum;63 int mx = 0;64 for (int i = 0; i < nums.size(); ++i)65 if (mask >> i & 1) {66 mx = max(mx, nums[i]);67 mn = min(mn, nums[i]);68 }69 return mx - mn;70 }71};72