Skip to content

Dynamic programming from a recurrence

Dynamic programming stores answers to subproblems that recur. The first task is to define what one stored answer means. A table without a precise state definition makes base cases and index choices difficult to justify.

This invented problem gives a row of integer rewards. Select positions with no two adjacent and maximize their sum. You may select no positions, so an empty input or an entirely negative input has value zero. The function returns the maximum value, not the chosen positions.

Let dp[i] mean the best total from the first i positions. If you skip the last position, the answer is dp[i - 1]. If you take it, you must skip its neighbor, so the answer is dp[i - 2] + rewards[i - 1].

For i >= 2, the recurrence is dp[i] = max(dp[i - 1], dp[i - 2] + rewards[i - 1]). The base cases are dp[0] = 0 and dp[1] = max(0, rewards[0]) when an element exists. These choices cover every valid solution because the last position is either selected or skipped.

Start with the direct recursive definition

Section titled “Start with the direct recursive definition”
def best_prefix_recursive(rewards: list[int], count: int) -> int:
"""Return the best nonadjacent reward from a prefix by recursion.
Args:
rewards: Integer rewards; selecting no position is allowed.
count: Prefix length between zero and len(rewards).
Returns:
The greatest sum from nonadjacent positions in the prefix.
"""
if count == 0:
return 0
if count == 1:
return max(0, rewards[0])
skip = best_prefix_recursive(rewards, count - 1)
take = rewards[count - 1] + best_prefix_recursive(rewards, count - 2)
return max(skip, take)
rewards = [4, 9, 3, 7, 6]
print("Recursive best reward:", best_prefix_recursive(rewards, len(rewards)))
Recursive best reward: 16

The recursive function expresses the decision clearly but solves the same prefix more than once. A call for five positions calls prefixes of four and three; the four-position call also asks for three. That repeated work expands as the input grows.

The call-count recurrence is Fibonacci-like, so time is exponential. O(2ⁿ) is a valid upper bound; the tighter growth rate is Theta(phiⁿ), where phi is the golden ratio. The maximum call depth is O(n), so auxiliary stack space is O(n). Exponential total calls do not mean exponential simultaneous stack space.

def reward_table(rewards: list[int]) -> list[int]:
"""Compute the best nonadjacent reward for every prefix.
Args:
rewards: Integer rewards; selecting no position is allowed.
Returns:
A list where entry i is the optimum for the first i positions.
"""
table = [0] * (len(rewards) + 1)
for count in range(1, len(rewards) + 1):
skip = table[count - 1]
previous = table[count - 2] if count >= 2 else 0
take = previous + rewards[count - 1]
table[count] = max(skip, take)
return table
table = reward_table(rewards)
print("Prefix table:", table)
print("prefix | skip | take | best")
for count in range(1, len(rewards) + 1):
skip = table[count - 1]
previous = table[count - 2] if count >= 2 else 0
take = previous + rewards[count - 1]
print(count, skip, take, table[count], sep=" | ")
print("Tabulated best reward:", table[-1])
Prefix table: [0, 4, 9, 9, 16, 16]
prefix | skip | take | best
1 | 0 | 4 | 4
2 | 4 | 9 | 9
3 | 9 | 7 | 9
4 | 9 | 16 | 16
5 | 16 | 15 | 16
Tabulated best reward: 16

Before iteration count, every smaller prefix has its correct optimum in the table. Both candidates therefore use correct subproblem answers. Taking their maximum produces the correct optimum for this prefix. The base entry and this invariant prove every later entry.

Under constant-time arithmetic, the function costs O(n) time and stores O(n) values. It returns the table, so that storage is output space for this function. If an interview asks only for the final total and you keep a table internally, the same storage counts as auxiliary space.

Keep only the states that the next step needs

Section titled “Keep only the states that the next step needs”

The recurrence uses only the preceding two prefix answers. Once the table version is correct, two variables can replace it when the task requests only the final total.

def best_reward(rewards: list[int]) -> int:
"""Return the best nonadjacent reward with constant auxiliary storage.
Args:
rewards: Integer rewards; selecting no position is allowed.
Returns:
The greatest sum from nonadjacent positions.
"""
two_back = 0
one_back = 0
for reward in rewards:
current = max(one_back, two_back + reward)
two_back, one_back = one_back, current
return one_back
print("Constant-space best reward:", best_reward(rewards))
for case in ([], [7], [-3, -1], [5, 1, 5], [4, 9, 3, 7, 6]):
expected = best_prefix_recursive(case, len(case))
assert reward_table(case)[-1] == expected
assert best_reward(case) == expected
print("The empty, singleton, negative, and separated-choice cases pass.")
Constant-space best reward: 16
The empty, singleton, negative, and separated-choice cases pass.

This function costs O(n) time and O(1) auxiliary space in the stated arithmetic model. Python integers can grow beyond one machine word. If rewards or accumulated sums have an unbounded number of bits, addition and comparison costs must include that bit length.

Keeping only two totals loses the decisions that produced the answer. A task that also requests the chosen positions needs a reconstruction method, such as retaining the prefix table and walking backward through its choices.

Memoization offers another route. It caches each recursive state on demand. For this recurrence it reduces repeated work to O(n) states, while retaining O(n) cache storage and O(n) call depth. Tabulation computes the same state dependency order without recursive calls.

The two-dimensional lesson extends the state to two string prefixes. It derives edit distance and explains when two rows can replace a full table.

Memoization preserves the recursive definition but stores each completed state. A cache for one fixed reward sequence needs only the prefix length as its key. The helper receives that cache explicitly, and the public function creates a fresh cache for each problem.

def cached_prefix_reward(
rewards: list[int], count: int, memo: dict[int, int]
) -> int:
"""Evaluate a prefix using a cache owned by one reward problem.
Args:
rewards: Fixed integer rewards that remain unchanged during the call.
count: Prefix length between zero and len(rewards).
memo: Correct cached answers for this same reward sequence.
Returns:
The greatest reward from nonadjacent positions in the prefix.
"""
if count in memo:
return memo[count]
if count == 0:
answer = 0
elif count == 1:
answer = max(0, rewards[0])
else:
skip = cached_prefix_reward(rewards, count - 1, memo)
take = rewards[count - 1] + cached_prefix_reward(
rewards, count - 2, memo
)
answer = max(skip, take)
memo[count] = answer
return answer
def best_reward_memoized(rewards: list[int]) -> int:
"""Return an optimum using a fresh recursive cache for this input.
Args:
rewards: Integer rewards; selecting nothing is permitted.
Returns:
The greatest sum obtainable without adjacent selected positions.
"""
return cached_prefix_reward(rewards, len(rewards), {})
prefix_cache = {}
print("Memoized optimum:", cached_prefix_reward(
rewards, len(rewards), prefix_cache
))
print("Completed states:", sorted(prefix_cache.items()))
print("A separate problem:", best_reward_memoized([1, 20, 1]))
print("Original problem again:", best_reward_memoized(rewards))
Memoized optimum: 16
Completed states: [(0, 0), (1, 4), (2, 9), (3, 9), (4, 16), (5, 16)]
A separate problem: 20
Original problem again: 16

Each missing state evaluates its recurrence once. There are O(n) states, so expected time is O(n) under the dictionary and arithmetic assumptions used elsewhere in the course. The cache and recursive call stack each use O(n) space. Memoization does not remove Python’s recursion-depth limit.

Do not reuse prefix_cache with another reward sequence. A prefix length identifies a state only within the fixed problem. The wrapper prevents this mistake by allocating a new dictionary for each call.

functools.cache supplies an alternative decorator with hashable argument keys. Its cache survives function calls and retains its arguments and results until cleared. A decorated implementation must also count any work needed to hash its keys, including a tuple that contains the whole input.

The maximum total does not identify its selected positions. Retain the prefix table, then walk backward. If the current value equals the preceding prefix value, skipping this position preserves an optimum. Otherwise the recurrence requires taking this position and moving back two positions.

This implementation prefers skipping a later position when both choices tie. It returns one optimum; it does not enumerate every optimal selection.

def best_reward_selection(rewards: list[int]) -> tuple[int, list[int]]:
"""Return an optimal total and one compatible selection of positions.
Args:
rewards: Integer rewards in input order. The input is unchanged.
Returns:
The maximum total and selected indices in increasing order. Ties
prefer skipping the later position, and selecting nothing is valid.
"""
table = reward_table(rewards)
selected = []
count = len(rewards)
while count > 0:
if table[count] == table[count - 1]:
count -= 1
else:
selected.append(count - 1)
count -= 2
selected.reverse()
return table[-1], selected
selection_total, selection_indices = best_reward_selection(rewards)
print("Optimal total:", selection_total)
print("Selected positions:", selection_indices)
print("Selected rewards:", [rewards[index] for index in selection_indices])
assert sum(rewards[index] for index in selection_indices) == selection_total
assert all(
right - left > 1
for left, right in zip(selection_indices, selection_indices[1:])
)
assert best_reward_selection([]) == (0, [])
assert best_reward_selection([-2, -1]) == (0, [])
assert best_reward_selection([5, 5]) == (5, [0])
print("Reconstructed totals, nonadjacency, empty inputs, and ties pass.")
Optimal total: 16
Selected positions: [1, 3]
Selected rewards: [9, 7]
Reconstructed totals, nonadjacency, empty inputs, and ties pass.

Each backward step removes one or two positions from consideration. The table and reconstruction therefore take O(n) time. The table occupies O(n) auxiliary space, and the returned indices occupy up to O(n) output space.

Climbing Stairs asks for a count rather than a maximum. Define the meaning of the empty-prefix base case before you write the recurrence.

House Robber uses a nonadjacent choice constraint. Explain why keeping only the largest single reward does not capture combinations of compatible positions.

Download the Python source to run the complete example locally.

MIT’s dynamic programming lecture notes develop state definitions, dependencies, and repeated subproblems. The first dynamic programming lecture gives another recurrence to analyze.

Python’s cache documentation describes memoization through argument-based lookup. Cached arguments must be hashable, so a list cannot be a direct cache key.