Dynamic programming (DP) solves a big problem by breaking it into smaller overlapping subproblems, solving each one only once and storing the answer. It turns many algorithms that would take exponential time into ones that run in polynomial time. DP is behind route planning, spell checkers, DNA comparison and resource allocation, and it is a favourite topic in coding interviews.
In this lesson you will learn
- The two signs that a problem suits DP
- Memoization (top-down) and tabulation (bottom-up)
- How DP turns millions of calls into a few dozen
- Solving the 0/1 knapsack problem with a table
- A step-by-step method for writing DP solutions
From Exponential to Linear: Fibonacci
#include <stdio.h>
static long calls;
long long fib_naive(int n) {
calls++;
return n < 2 ? n : fib_naive(n - 1) + fib_naive(n - 2);
}
long long memo[100];
long long fib_memo(int n) { /* top-down: remember answers */
calls++;
if (n < 2) return n;
if (memo[n]) return memo[n];
return memo[n] = fib_memo(n - 1) + fib_memo(n - 2);
}
long long fib_table(int n) { /* bottom-up: fill a table */
long long prev = 0, cur = 1;
if (n == 0) return 0;
for (int i = 2; i <= n; i++) {
long long next = prev + cur;
prev = cur;
cur = next;
}
return cur;
}
int main(void) {
int n = 30;
calls = 0;
long long a = fib_naive(n);
printf("Naive recursion: fib(%d) = %lld using %ld calls\n", n, a, calls);
calls = 0;
long long b = fib_memo(n);
printf("Memoization: fib(%d) = %lld using %ld calls\n", n, b, calls);
printf("Tabulation: fib(%d) = %lld using one loop\n", n, fib_table(n));
printf("fib(90) = %lld\n", fib_table(90));
return 0;
}
Output
Naive recursion: fib(30) = 832040 using 2692537 calls
Memoization: fib(30) = 832040 using 59 calls
Tabulation: fib(30) = 832040 using one loop
fib(90) = 2880067194370816120
- The naive version recalculates the same values again and again:
fib(28)is computed twice,fib(27)three times, and so on. That is 2.7 million calls for n = 30, and the count roughly multiplies by 1.6 for every extra step of n. - Memoization (top-down) keeps the recursive code but stores each answer in
memothe first time it is computed. Later calls return the stored value, so only 59 calls are needed. - Tabulation (bottom-up) builds answers from the smallest case upwards in a loop. Here only the last two values are needed, so it uses O(1) memory.
long longis used because Fibonacci numbers grow quickly;fib(90)needs 62 bits.
When Does DP Apply?
| Property | Meaning |
|---|---|
| Overlapping subproblems | The same smaller problems come up repeatedly |
| Optimal substructure | The best answer can be built from the best answers to smaller problems |
Merge sort has optimal substructure but its subproblems do not overlap, so it is “divide and conquer” rather than DP.
The 0/1 Knapsack Problem
A bag holds at most 5 kg. Each item has a weight and a value and can be taken once or not at all. Which items give the largest total value?
#include <stdio.h>
/* 0/1 knapsack: best value with total weight <= W, each item used once */
int max(int a, int b) { return a > b ? a : b; }
int main(void) {
const char *name[] = {"laptop", "camera", "book", "jacket"};
int weight[] = {3, 2, 1, 2};
int value[] = {2000, 1500, 300, 800};
int n = 4, W = 5;
int dp[5][6] = {0}; /* dp[i][w]: first i items, capacity w */
for (int i = 1; i <= n; i++) {
for (int w = 0; w <= W; w++) {
dp[i][w] = dp[i - 1][w]; /* skip item */
if (weight[i - 1] <= w) /* or take it */
dp[i][w] = max(dp[i][w], dp[i - 1][w - weight[i - 1]] + value[i - 1]);
}
}
printf("Best value with capacity %d: %d\n", W, dp[n][W]);
printf("Items taken: ");
for (int i = n, w = W; i > 0; i--) { /* trace back */
if (dp[i][w] != dp[i - 1][w]) {
printf("%s ", name[i - 1]);
w -= weight[i - 1];
}
}
printf("\n");
return 0;
}
Output
Best value with capacity 5: 3500
Items taken: camera laptop
- State:
dp[i][w]is the best value using the firstiitems with capacityw. - Choice: for each item, either skip it (
dp[i-1][w]) or take it if it fits (its value plusdp[i-1][w - weight]). Keep the larger. - Answer:
dp[n][W], here 3500 taka from the laptop (3 kg) and camera (2 kg). - Trace-back: walking backwards through the table shows which items were taken. Whenever a value differs from the row above, that item was used.
- The table has (n + 1) × (W + 1) cells, so the time and memory are O(n·W), far less than the 2n combinations a brute-force search would try.
A Recipe for DP Problems
- Define the state: what does
dp[...]mean in words? - Write the recurrence: how does a state depend on smaller ones?
- Set the base cases.
- Choose the order of filling (or use memoization).
- Read the answer, and trace back if you need the actual choices.
Classic problems to practise: climbing stairs, coin change, longest common subsequence, edit distance, longest increasing subsequence. Kadane’s algorithm for the maximum subarray is also a compact DP.
Common Mistakes
- Vague state definitions, which make the recurrence impossible to get right.
- Wrong base cases or table sizes off by one.
- Filling the table in an order where a cell needs values not yet computed.
- Using a memo value of 0 to mean “not computed” when 0 can be a real answer; use −1 or a separate flag.
Practice Exercises
Exercise 1. You can climb 1 or 2 steps at a time. In how many ways can you climb 10 steps?
Show answer
int ways[11] = {1, 1}; /* ways[0] = 1, ways[1] = 1 */
for (int i = 2; i <= 10; i++) ways[i] = ways[i - 1] + ways[i - 2];
printf("%d\n", ways[10]); /* 89 */
The last move is either 1 step or 2 steps, so the counts add up, and the pattern is Fibonacci again.
Exercise 2. Find the minimum number of coins to make 11 using coins of 1, 2 and 5.
Show answer
int coins[] = {1, 2, 5}, best[12];
best[0] = 0;
for (int a = 1; a <= 11; a++) {
best[a] = 1000;
for (int c = 0; c < 3; c++)
if (coins[c] <= a && best[a - coins[c]] + 1 < best[a])
best[a] = best[a - coins[c]] + 1;
}
printf("%d\n", best[11]); /* 3 coins: 5 + 5 + 1 */
Frequently Asked Questions
Should I use memoization or tabulation?
Memoization is often easier to write because it follows the recursive definition and only computes the states actually needed. Tabulation avoids deep recursion, is usually faster, and makes memory savings easier.
Is a greedy algorithm the same as DP?
No. A greedy algorithm makes one locally best choice and never reconsiders it. DP considers all choices for each subproblem. Greedy works only for some problems; for example, it fails on coin change with coins of 1, 3 and 4 for the amount 6.
Summary
- DP stores answers to overlapping subproblems so each is solved once.
- Memoization is top-down recursion with a cache; tabulation fills a table bottom-up.
- Define the state, recurrence and base cases first.
- Knapsack shows how a table replaces an exponential search.
Next: Backtracking in C.
