- 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 Python from the credited upstream file form-largest-integer-with-digits-that-add-up-to-target.py.
- The implementation visibly relies on sequence storage, ordered lookup, 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.
123 4class Solution(object):5 def largestNumber(self, cost, target):6 """7 :type cost: List[int]8 :type target: int9 :rtype: str10 """11 dp = [0]12 for t in xrange(1, target+1):13 dp.append(-1)14 for i, c in enumerate(cost):15 if t-c < 0 or dp[t-c] < 0:16 continue17 dp[t] = max(dp[t], dp[t-c]+1)18 if dp[target] < 0:19 return "0"20 result = []21 for i in reversed(xrange(9)):22 while target >= cost[i] and dp[target] == dp[target-cost[i]]+1:23 target -= cost[i]24 result.append(i+1)25 return "".join(map(str, result))26 27 282930class Solution2(object):31 def largestNumber(self, cost, target):32 """33 :type cost: List[int]34 :type target: int35 :rtype: str36 """37 def key(bag):38 return sum(bag), bag39 40 dp = [[0]*9]41 for t in xrange(1, target+1):42 dp.append([])43 for d, c in enumerate(cost):44 if t < c or not dp[t-c]:45 continue46 curr = dp[t-c][:]47 curr[~d] += 148 if key(curr) > key(dp[t]):49 dp[-1] = curr 50 if not dp[-1]:51 return "0"52 return "".join(str(9-i)*c for i, c in enumerate(dp[-1]))53 54 555657class Solution3(object):58 def largestNumber(self, cost, target):59 """60 :type cost: List[int]61 :type target: int62 :rtype: str63 """64 dp = [0]65 for t in xrange(1, target+1):66 dp.append(-1)67 for i, c in enumerate(cost):68 if t-c < 0:69 continue70 dp[t] = max(dp[t], dp[t-c]*10 + i+1)71 return str(max(dp[t], 0))72