Dynamic programming
Advanced · 12 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Dynamic programming solves a big problem by solving its smaller parts once, writing the answers in a table, and reusing them instead of recalculating. It turns problems that repeat the same work endlessly into quick ones.
Practical use cases
- Web app: Fewest coins for a payment. A wallet app has to pay an exact amount with the fewest notes and coins from unusual denominations. A table stores the fewest coins needed for every amount from 1 up, building each from smaller amounts, so the answer for any amount is read instantly.
- Web app: Spell correction and text diff. A search box suggests "did you mean...?" by measuring how many edits turn one word into another. A table of edit costs for the starts of the two words avoids recomputing the same sub-pieces, so suggestions appear as the user types. The "changes" view in a document editor works the same way.
- Web app: Bundle that fits a budget and weight limit. A shopping or shipping app picks the most valuable items fitting a weight limit. A table of the best value for each weight limit as items are considered one by one gives the best bundle without trying every combination. The bundle is chosen in seconds, because each weight limit is solved once instead of trying every combination of products.
- System: Route and stock planning. Planning tools find cheapest routes or best times to buy and sell by storing the best result for each earlier stage. Each stage reuses the best result of the stage before, so even long trips are planned without trying every path.
The story: Raju’s Pocket Change
A customer handed Raju ₹11 for a chai and he wanted to give change using as few coins as possible from his ₹1, ₹2 and ₹5 coins. Mira tried the greedy trick: biggest coin first. ₹5, ₹5, ₹1 = three coins. It worked! But Kabir said: "With coins 1, 3, 4 and amount 6, greedy picks 4+1+1, but 3+3 is better." Greedy was lying.
So Mira thought differently: "Suppose I already know the best answer for every smaller amount. For ₹11, I could last use a ₹1 coin (then I need best(₹10) + 1), or a ₹2 coin (best(₹9) + 1), or a ₹5 coin (best(₹6) + 1). Take the smallest." The big problem is made of smaller copies of itself, and those smaller copies repeat.
Plain recursion would solve "best for ₹6" again and again from different branches. So Mira wrote the answers in a table, from ₹0 upwards. Each answer is computed once, using only cells already filled. ₹0 = 0 coins, ₹1 = 1, ₹2 = 1, ₹3 = 2... up to ₹11 = 3.
That is dynamic programming. The smell: "minimum / maximum / how many ways", choices at each step, the same smaller sub-question showing up repeatedly, and greedy does not hold. Define the state (what a table cell means), the recurrence (how a cell uses earlier cells), and fill in order.
How to spot this problem, and where you need it
A problem asks for the best, smallest, largest or count of ways, and a simple recursive solution keeps recomputing the same sub-answers again and again, getting very slow.
Signs you need it
- The wording is "minimum number of...", "maximum value...", "number of ways to...", "longest sequence...".
- A recursive solution works for tiny input but takes forever on slightly larger ones because the same calls repeat.
- The answer for a bigger case can be built from answers for smaller cases.
Where to use it in a project
- Pricing, change-making, bundling and budget optimizers in shops and wallets.
- Text comparison, diff and fuzzy-search features that suggest corrections.
- Planning screens for routes, schedules and investments built stage by stage.
The solution
Define what a sub-problem is (for example, "fewest coins for amount a"). Write how a bigger sub-problem is made from smaller ones. Then fill a table in order from the smallest, or use a cache (memoization) in recursion, so each sub-problem is computed once. The last cell or the cached top call holds the answer.
Payoff: Before: a recursive solution making billions of repeated calls. After: a table of a few thousand cells filled once.
Explain it like I am 8
Imagine climbing a staircase and writing on each step how many ways there are to reach it. To fill step 10, you just peek at your notes on step 9 and step 8. You never recount from the ground floor; you reuse your notes.
How it works, step by step
- Spot the clue: an optimisation or counting question where the big answer is built from smaller answers that overlap.
- Define the state: what does one table cell mean? Here
dp[x]= fewest coins to make amountx. - Write the recurrence:
dp[x] = 1 + min(dp[x - coin])over every coin that fits. - Set the base case (
dp[0] = 0) and a "impossible" marker for everything else. - Fill in order from small to big, then read the answer from
dp[amount]. If it is still "impossible", return -1.
The code in four languages
PHP
<?php
// Classic: "Coin Change": the fewest coins for an amount (or -1).
function fewestCoins(array $coins, int $amount): int {
$impossible = PHP_INT_MAX;
$dp = array_fill(0, $amount + 1, $impossible); // dp[x] = fewest coins for amount x
$dp[0] = 0; // base case: 0 rupees needs 0 coins
for ($x = 1; $x <= $amount; $x++) {
foreach ($coins as $coin) {
if ($coin <= $x && $dp[$x - $coin] !== $impossible) {
$dp[$x] = min($dp[$x], $dp[$x - $coin] + 1); // reuse an earlier cell
}
}
}
return $dp[$amount] === $impossible ? -1 : $dp[$amount];
}
echo fewestCoins([1, 2, 5], 11), "
"; // 3 (5 + 5 + 1)
echo fewestCoins([1, 3, 4], 6), "
"; // 2 (3 + 3, greedy would say 3)
echo fewestCoins([2], 3), "
"; // -1 (impossible)JavaScript
// Classic: "Coin Change": the fewest coins for an amount (or -1).
function fewestCoins(coins, amount) {
const dp = new Array(amount + 1).fill(Infinity); // dp[x] = fewest coins for amount x
dp[0] = 0; // base case: 0 rupees needs 0 coins
for (let x = 1; x <= amount; x++) {
for (const coin of coins) {
if (coin <= x) {
dp[x] = Math.min(dp[x], dp[x - coin] + 1); // reuse an earlier cell
}
}
}
return dp[amount] === Infinity ? -1 : dp[amount];
}
console.log(fewestCoins([1, 2, 5], 11)); // 3 (5 + 5 + 1)
console.log(fewestCoins([1, 3, 4], 6)); // 2 (3 + 3, greedy would say 3)
console.log(fewestCoins([2], 3)); // -1 (impossible)Java
import java.util.*;
public class Main {
// Classic: "Coin Change": the fewest coins for an amount (or -1).
static int fewestCoins(int[] coins, int amount) {
int impossible = Integer.MAX_VALUE;
int[] dp = new int[amount + 1]; // dp[x] = fewest coins for amount x
Arrays.fill(dp, impossible);
dp[0] = 0; // base case: 0 rupees needs 0 coins
for (int x = 1; x <= amount; x++) {
for (int coin : coins) {
if (coin <= x && dp[x - coin] != impossible) {
dp[x] = Math.min(dp[x], dp[x - coin] + 1); // reuse an earlier cell
}
}
}
return dp[amount] == impossible ? -1 : dp[amount];
}
public static void main(String[] args) {
System.out.println(fewestCoins(new int[]{1, 2, 5}, 11)); // 3 (5 + 5 + 1)
System.out.println(fewestCoins(new int[]{1, 3, 4}, 6)); // 2 (3 + 3, greedy would say 3)
System.out.println(fewestCoins(new int[]{2}, 3)); // -1 (impossible)
}
}Go
package main
import (
"fmt"
"math"
)
// fewestCoins is the classic "Coin Change": the fewest coins for an amount (or -1).
func fewestCoins(coins []int, amount int) int {
const impossible = math.MaxInt
dp := make([]int, amount+1) // dp[x] = fewest coins for amount x
for x := range dp {
dp[x] = impossible
}
dp[0] = 0 // base case: 0 rupees needs 0 coins
for x := 1; x <= amount; x++ {
for _, coin := range coins {
if coin <= x && dp[x-coin] != impossible {
dp[x] = min(dp[x], dp[x-coin]+1) // reuse an earlier cell
}
}
}
if dp[amount] == impossible {
return -1
}
return dp[amount]
}
func main() {
fmt.Println(fewestCoins([]int{1, 2, 5}, 11)) // 3 (5 + 5 + 1)
fmt.Println(fewestCoins([]int{1, 3, 4}, 6)) // 2 (3 + 3, greedy would say 3)
fmt.Println(fewestCoins([]int{2}, 3)) // -1 (impossible)
}Time: O(amount × coins) · Extra space: O(amount). One table cell per amount, and each cell tries every coin once.
Watch out for
- Not initialising "impossible" cells properly, then adding 1 to the marker and overflowing (a PHP integer trap).
- Using greedy when choices interact. Always test with a counter-example like coins 1, 3, 4.
- Choosing a state that does not capture everything needed to make the next decision, so the recurrence gives wrong answers.
Quick check
- Which clue says "think dynamic programming"?
- "reverse a string"
- "minimum number of coins / count the ways", with repeated sub-questions
- "find the middle of a list"
- "print a sorted list"
- What does dp[0] = 0 mean here?
- Zero coins exist
- The answer is zero
- Making ₹0 needs zero coins (the base case)
- The table is empty
- What is the advantage over plain recursion?
- Less code
- It needs no base case
- It works on any problem
- Each sub-problem is solved once and reused