Data Structures & Algorithms / Module 9: Dynamic programming
Topic 9.3
Knapsack, LCS and coin change
Coin change, LCS and knapsack: three DP problems that keep coming up, with one shared pattern.
Watch: each cell is worked out from earlier cells. For change of 6 with coins 1, 3 and 4, this finds 2 coins, not 3.
- moving now
- being checked
- finished / the result
Coin change
dp[a] = the fewest coins for amount a. The last coin used must be one of the coins available. If the last coin is c, what remains is a − c, and its answer is already in the table. Try every coin, take the best. With coins 1, 3, 4 and amount 6, greedy (Module 5) gave 4 + 1 + 1. DP finds 3 + 3.
Code, for programmersCoin change
function fewestCoins(coins, amount) {
const dp = [0, ...Array(amount).fill(Infinity)]; // Infinity = not possible yet
for (let a = 1; a <= amount; a++) {
for (const c of coins) {
if (c <= a) dp[a] = Math.min(dp[a], dp[a - c] + 1); // c as the last coin
}
}
return dp[amount] === Infinity ? -1 : dp[amount];
}LCS: the longest common subsequence
dp[i][j] = the LCS length of the first i letters of the first word and the first j of the second. If the last letters match, use that letter: diagonal + 1. If not, one of them can't be used: take the best of above or left. Git diff compares lines, not letters, with the same idea: lines in the LCS are unchanged, the rest show up as additions or deletions.
Code, for programmersLCS
function lcs(a, b) {
const dp = Array.from({ length: a.length + 1 }, () => Array(b.length + 1).fill(0));
for (let i = 1; i <= a.length; i++) {
for (let j = 1; j <= b.length; j++) {
dp[i][j] = a[i - 1] === b[j - 1]
? dp[i - 1][j - 1] + 1 // same letter: keep it
: Math.max(dp[i - 1][j], dp[i][j - 1]); // drop one of the two
}
}
return dp[a.length][b.length];
}
lcs("CAKE", "COKE"); // 3 ("CKE")Knapsack
You have a bag with capacity W and items, each with a weight and a value. Each item can be taken at most once. dp[w] = the best value with capacity w. For each item there are two choices: leave it (value unchanged), or take it (add its value, lose its weight in capacity). Real examples: choosing which features fit a time-boxed sprint, or which ads fill a slot.
Code, for programmers0/1 knapsack
function knapsack(items, capacity) { // items: [{ weight, value }]
const dp = Array(capacity + 1).fill(0);
for (const { weight, value } of items) {
for (let w = capacity; w >= weight; w--) { // backwards, so each item is used once
dp[w] = Math.max(dp[w], dp[w - weight] + value);
}
}
return dp[capacity];
}Quiz
Coin change: dp[a] is worked out from…
LCS: letters a[i-1] and b[j-1] match. dp[i][j] = …
In 0/1 knapsack, why does the w loop run backwards?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.