Reduce Dynamic Programming Storage Safely
Core idea
If each new DP state depends only on a fixed number of previous states, retain those values instead of the full table. For the tile-cost recurrence, two variables are enough to compute the minimum total in O(n) arithmetic operations and O(1) auxiliary stored values. Preserve old dependencies until the new value is computed; this optimization does not keep a reconstructable path.
cost = [2,8,1,4]a,b = cost[0], cost[0]+cost[1]for x in cost[2:]: a,b = b,x+min(a,b)print(b)The right side reads both old values before assignment. This compact demonstration slices the input; the next example avoids that extra allocation.
Avoid the input slice
def cheapest(cost): if len(cost)==1: return cost[0] a,b=cost[0],cost[0]+cost[1] for i in range(2,len(cost)): a,b=b,cost[i]+min(a,b) return bprint(cheapest([3,1,5,2,1]))Only the last two costs are retained; input is nonempty.
Common mistake
Updating a=b before computing the new b overwrites the older predecessor. Also, constant auxiliary values do not mean constant total memory if input or large integers dominate.
Practice
Compare the table and rolling algorithms on a one-tile, two-tile and five-tile input. Explain why reconstructing the path needs extra work.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Space optimization
Check your understanding of space optimization.
What is printed?
a,b=2,10a,b=b,1+min(a,b)print(a,b)What is printed?
a,b=2,10a=bb=1+min(a,b)print(b)When is rolling storage safe?
What is lost by dropping the full table?