← All questions
RareProgramming

How can a dynamic programming algorithm use less memory?

Short answer
Keep one array when only recent states are needed

Exercise

  1. Make more recursive calls
  2. Keep one array when only recent states are needed
  3. Enlarge the table
  4. Switch to a greedy algorithm
  5. 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.

Dynamic programming

Platforms

  • MAXIMUM

Download now and try it for free on your own tasks!

10 15 free credits • No credit card required
Version: Loading…

Choose the Windows app or the Chrome extension with phone controls.