Loading...
Master memoization, tabulation, and advanced DP patterns
Section 2 of 5
When to choose top-down vs bottom-up, ordering, and space optimization.
Given prices for pieces of length 1..n, find the maximum revenue for a rod of length n. Try all first cuts and combine with the best for the remaining length.
1function rodCut(n, price):2 memo = array(n+1, -INF)3 function f(len):4 if len == 0: return 05 if memo[len] != -INF: return memo[len]6 best = 07 for cut in 1..len:8 best = max(best, price[cut] + f(len - cut))9 memo[len] = best10 return best11 return f(n)1function rodCutTab(n, price):2 dp = array(n+1, 0)3 for len in 1..n:4 best = 05 for cut in 1..len:6 best = max(best, price[cut] + dp[len - cut])7 dp[len] = best8 return dp[n]