- 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
- 59 lines of C++ from the credited upstream file 3444.cpp.
- The implementation visibly relies on sequence storage, hash lookup, cached states.
- 7 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 minimumIncrements(vector<int>& nums, vector<int>& target) {4 const int maxMask = 1 << target.size();5 unordered_map<int, long> maskToLcm;6 7 for (int mask = 1; mask < maxMask; ++mask) {8 const vector<int> subset = getSubset(mask, target);9 maskToLcm[mask] = getLcm(subset);10 }11 12 13 14 15 vector<long> dp(maxMask, LONG_MAX);16 dp[0] = 0;17 18 for (const int num : nums) {19 20 21 22 23 vector<pair<int, long>> maskToCost;24 for (const auto& [mask, lcm] : maskToLcm) {25 const int remainder = num % lcm;26 maskToCost.emplace_back(mask, remainder == 0 ? 0 : lcm - remainder);27 }28 vector<long> newDp = dp;29 for (int prevMask = 0; prevMask < maxMask; ++prevMask) {30 if (dp[prevMask] == LONG_MAX)31 continue;32 for (const auto& [mask, cost] : maskToCost) {33 const int newMask = prevMask | mask;34 newDp[newMask] = min(newDp[newMask], dp[prevMask] + cost);35 }36 }37 dp = std::move(newDp);38 }39 40 return dp.back() == LONG_MAX ? -1 : dp.back();41 }42 43 private:44 vector<int> getSubset(int mask, const vector<int>& target) {45 vector<int> subset;46 for (int i = 0; i < target.size(); ++i)47 if (mask >> i & 1)48 subset.push_back(target[i]);49 return subset;50 }51 52 long getLcm(const vector<int>& nums) {53 long res = 1;54 for (const int num : nums)55 res = lcm(res, num);56 return res;57 }58};59