- 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 Python from the credited upstream file maximum-number-of-items-from-sale-i.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 maximumSaleItems(self, items, budget):7 """8 :type items: List[List[int]]9 :type budget: int10 :rtype: int11 """12 NEG_INF = float("-inf")13 cnt = [0]*(max(f for f, _ in items)+1)14 for f, _ in items:15 cnt[f] += 116 total = [0]*len(cnt)17 for i in xrange(1, len(total)):18 if not cnt[i]:19 continue20 for j in xrange(i, len(total), i):21 total[i] += cnt[j]22 dp = [NEG_INF]*(budget+1)23 dp[0] = 024 for f, p in items:25 for i in reversed(xrange(p, len(dp))):26 dp[i] = max(dp[i], dp[i-p]+total[f])27 min_p = min(p for _, p in items)28 return max(x+(budget-i)min_p for i, x in enumerate(dp))29 30 31323334class Solution2(object):35 def maximumSaleItems(self, items, budget):36 """37 :type items: List[List[int]]38 :type budget: int39 :rtype: int40 """41 NEG_INF = float("-inf")42 cnt = [0]*(max(f for f, _ in items)+1)43 for f, _ in items:44 cnt[f] += 145 total = [0]*len(cnt)46 for i in xrange(1, len(total)):47 if not cnt[i]:48 continue49 for j in xrange(i, len(total), i):50 total[i] += cnt[j]51 dp = [NEG_INF]*(budget+1)52 dp[0] = 053 for f, p in items:54 for i in reversed(xrange(p, len(dp))):55 dp[i] = max(dp[i], dp[i-p]+total[f])56 for i in xrange(p, len(dp)):57 dp[i] = max(dp[i], dp[i-p]+1)58 return max(dp)59