- 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 3444.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered 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 int minimumIncrements(int[] nums, int[] target) {3 final int maxMask = 1 << target.length;4 Map<Integer, Long> maskToLcm = new HashMap<>();5 6 for (int mask = 1; mask < maxMask; ++mask) {7 List<Integer> subset = getSubset(mask, target);8 maskToLcm.put(mask, getLcm(subset));9 }10 11 12 13 14 long[] dp = new long[maxMask];15 Arrays.fill(dp, Long.MAX_VALUE);16 dp[0] = 0;17 18 for (final int num : nums) {19 20 21 22 23 List<Pair<Integer, Long>> maskToCost = new ArrayList<>();24 for (Map.Entry<Integer, Long> entry : maskToLcm.entrySet()) {25 final int mask = entry.getKey();26 final long lcm = entry.getValue();27 final long remainder = num % lcm;28 maskToCost.add(new Pair<>(mask, remainder == 0 ? 0 : lcm - remainder));29 }30 long[] newDp = dp.clone();31 for (int prevMask = 0; prevMask < maxMask; ++prevMask) {32 if (dp[prevMask] == Long.MAX_VALUE)33 continue;34 for (Pair<Integer, Long> pair : maskToCost) {35 final int mask = pair.getKey();36 final long cost = pair.getValue();37 final int newMask = prevMask | mask;38 newDp[newMask] = Math.min(newDp[newMask], dp[prevMask] + cost);39 }40 }41 dp = newDp;42 }43 44 return dp[maxMask - 1] == Long.MAX_VALUE ? -1 : (int) dp[maxMask - 1];45 }46 47 private List<Integer> getSubset(int mask, int[] target) {48 List<Integer> subset = new ArrayList<>();49 for (int i = 0; i < target.length; ++i)50 if ((mask >> i & 1) == 1)51 subset.add(target[i]);52 return subset;53 }54 55 private long getLcm(List<Integer> nums) {56 long res = 1;57 for (final int num : nums)58 res = lcm(res, num);59 return res;60 }61 62 private long lcm(long a, long b) {63 return a * b / gcd(a, b);64 }65 66 private long gcd(long a, long b) {67 return b == 0 ? a : gcd(b, a % b);68 }69}70