RareProgramming
How can a dynamic programming algorithm use less memory?
Short answer
Keep one array when only recent states are needed
Exercise
- Make more recursive calls
- Keep one array when only recent states are needed
- Enlarge the table
- Switch to a greedy algorithm
- Use more complex data structures
Solution
A row can be overwritten once its old values are no longer needed.
Consider grid paths moving right or down. Scanning left to right, the old current cell counts paths from above and its left neighbour already carries the new row's sum. Each row becomes the next in place, so storage depends on the grid's width.
G(r,c) = G(r−1,c) + G(r,c−1). row[c] ← row[c] + row[c−1]. [1, 2, 3] → [1, 3, 6].
First identify what the next transition reads. A cell may be overwritten only after its old value has been used for the last time. Recovering an entire path can require extra information even when computing its value does not.
Platforms
- MAXIMUM
