- 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
- 42 lines of Python from the credited upstream file maximum-weight-in-two-bags.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.
123 45class Solution(object):6 def maxWeight(self, weights, w1, w2):7 """8 :type weights: List[int]9 :type w1: int10 :type w2: int11 :rtype: int12 """13 dp = [[False]*(w2+1) for _ in xrange(w1+1)]14 dp[0][0] = True15 for w in weights:16 dp = [[dp[i][j] or (i-w >= 0 and dp[i-w][j]) or (j-w >= 0 and dp[i][j-w]) for j in xrange(w2+1)] for i in xrange(w1+1)]17 result = 018 for i in xrange(w1+1):19 for j in reversed(xrange(w2+1)):20 if dp[i][j]:21 result = max(result, i+j)22 break23 return result24 25 26272829class Solution2(object):30 def maxWeight(self, weights, w1, w2):31 """32 :type weights: List[int]33 :type w1: int34 :type w2: int35 :rtype: int36 """37 dp = [[False]*(w2+1) for _ in xrange(w1+1)]38 dp[0][0] = True39 for w in weights:40 dp = [[dp[i][j] or (i-w >= 0 and dp[i-w][j]) or (j-w >= 0 and dp[i][j-w]) for j in xrange(w2+1)] for i in xrange(w1+1)]41 return max(i+j for i in xrange(w1+1) for j in xrange(w2+1) if dp[i][j])42