Module P-12·16 min read

House robber, coin change, decode ways — and how to define what dp[i] actually represents.

JJS
Written by Jatin Jain Saraf · Senior Software Engineer

Module P-12 — Dynamic Programming II: Classic 1D Problems

What this module covers: Module P-11 covered the mechanics — memoization and tabulation are close to mechanical once you know the recurrence. The actual skill in dynamic programming is figuring out what table[i] should represent in the first place. This module works through three classic problems where that state definition is the real challenge, each with a different shape of recurrence.


The Real Question: What Does dp[i] Mean?

Every 1D DP problem starts with the same question: if dp[i] holds "the answer to this problem, restricted to just the first i elements," what's the relationship between dp[i] and the smaller answers before it? Get that relationship right, and the rest — memoization or tabulation — is mechanical, exactly as Module P-11 showed.


House Robber: Choose or Skip

You're robbing houses along a street; adjacent houses can't both be robbed (the alarm links them). Maximize total loot.

typescript

The state definition is: dp[i] = best possible loot using only houses 0 through i. The recurrence falls directly out of the problem's one constraint — you can't rob two adjacent houses, so robbing house i forces you to have skipped house i - 1, meaning the best you can add to is dp[i - 2], not dp[i - 1]. Skipping house i entirely just carries forward whatever dp[i - 1] already was. This is the same "only look back a fixed number of steps" shape as Module P-11's Fibonacci, so the same O(1)-space trick applies — only dp[i-1] and dp[i-2] are ever needed.


Coin Change: Minimum Coins to Reach an Amount

Given coin denominations and a target amount, find the minimum number of coins needed (or determine it's impossible).

typescript

Here dp[a] = the minimum coins needed to make amount a exactly. For each amount, the recurrence tries every coin denomination: if you use one coin of value coin, the remaining amount to cover is a - coin, which has already been solved (it's smaller, and the loop processes amounts in increasing order) — so dp[a - coin] + 1 is a candidate answer, and you take the minimum across all coins tried. This is a genuinely different recurrence shape from House Robber: instead of only ever looking back 1 or 2 fixed steps, it looks back by a variable amount (coin, for each denomination), which is exactly why this can't be compressed to O(1) space the way Fibonacci and House Robber could — every entry in dp might still be needed by some later amount, depending on the coin denominations available.


Decode Ways: Counting Ambiguous Interpretations

Sign in to keep reading

The rest of this module is free — sign in with Google to unlock it and track your progress.

Sign in & Register

Discussion

0

Join the discussion

Loading comments...

© 2026 Jatin Jain Saraf (JJS). All rights reserved.