14.5 Unbounded knapsack problem¶
We will now solve another common knapsack variant, unbounded knapsack, and then examine a special case: coin change.
14.5.1 Unbounded knapsack¶
Question
Given \(n\) items, where item \(i\) has weight \(wgt[i-1]\) and value \(val[i-1]\), and a knapsack of capacity \(cap\), each item may be chosen repeatedly. What is the maximum value that fits within the capacity? An example is shown in Figure 14-22.
Figure 14-22 Example input for unbounded knapsack
Description of Figure 14-22: Unbounded knapsack example: items may be chosen repeatedly
Unbounded knapsack allows choosing items of the same kind repeatedly; the figure shows the optimal selection for capacity 50.
Given 5 candidate items and knapsack capacity cap = 50, each item may be chosen any number of times provided the total weight does not exceed 50. This figure is a standalone capacity 50 example; the single-row update in Figure 14-23 below switches to capacity 4 and a different dataset of weights 1/2/3 that shares some fruit names but differs in IDs and weights.
On the left, a table lists ID i, weight wgt[i-1], and value val[i-1], with a fruit icon identifying each row's item. The apple row is highlighted in light purple and the banana row in light orange, labeled "×1" and "×2" beside two arrows pointing to the knapsack on the right labeled "Knapsack capacity cap = 50". The table below combines the item data with the quantities selected in the figure; 0 for the remaining items means no arrow selects them.
At the bottom, the figure explicitly notes "Maximum value: 290" and uses fruit icons to show packing one apple and two bananas into the knapsack, using 50 units of capacity in total.
| ID | Item | Weight | Value | Selected count in figure |
|---|---|---|---|---|
| 1 | Apple | 10 | 50 | 1 |
| 2 | Banana | 20 | 120 | 2 |
| 3 | Grapes | 30 | 150 | 0 |
| 4 | Pineapple | 40 | 210 | 0 |
| 5 | Watermelon | 50 | 240 | 0 |
Checking the arithmetic from the input: total weight is 10 + 2 × 20 = 50 and total value is 50 + 2 × 120 = 290, matching the conclusion at the bottom of the figure. If each item could be chosen at most once, the optimal choice for the same input would be banana plus grapes, with weight 20 + 30 = 50 and value 120 + 150 = 270; this comparison is derived from the input rather than drawn in the figure. Allowing repeated selection of bananas raises the maximum value to 290.
1. Dynamic programming approach¶
Unbounded knapsack is very similar to 0-1 knapsack. The only difference is that there is no limit on how many times an item may be chosen.
- In 0-1 knapsack, there is only one of each item, so after including item \(i\), we can choose only from the first \(i-1\) items.
- In unbounded knapsack, each item has an unlimited supply, so after including item \(i\), we can still choose from the first \(i\) items.
For unbounded knapsack, state \([i, c]\) has two cases.
- Leave item \(i\) out: As in 0-1 knapsack, the remaining state is \([i-1, c]\).
- Put item \(i\) in: Unlike 0-1 knapsack, the remaining state is \([i, c-wgt[i-1]]\).
The state transition equation becomes:
2. Code implementation¶
Compared with 0-1 knapsack, only one \(i-1\) in the transition changes to \(i\); the rest of the code is identical:
def unbounded_knapsack_dp(wgt: list[int], val: list[int], cap: int) -> int:
"""Unbounded knapsack: dynamic programming"""
n = len(wgt)
# Initialize the dp table
dp = [[0] * (cap + 1) for _ in range(n + 1)]
# State transitions
for i in range(1, n + 1):
for c in range(1, cap + 1):
if wgt[i - 1] > c:
# If item i exceeds the remaining capacity, do not choose it
dp[i][c] = dp[i - 1][c]
else:
# Take the larger value obtained by excluding and including item i
dp[i][c] = max(dp[i - 1][c], dp[i][c - wgt[i - 1]] + val[i - 1])
return dp[n][cap]
/* Unbounded knapsack: dynamic programming */
int unboundedKnapsackDP(vector<int> &wgt, vector<int> &val, int cap) {
int n = wgt.size();
// Initialize the dp table
vector<vector<int>> dp(n + 1, vector<int>(cap + 1, 0));
// State transitions
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If item i exceeds the remaining capacity, do not choose it
dp[i][c] = dp[i - 1][c];
} else {
// Take the larger value obtained by excluding and including item i
dp[i][c] = max(dp[i - 1][c], dp[i][c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[n][cap];
}
/* Unbounded knapsack: dynamic programming */
int unboundedKnapsackDP(int[] wgt, int[] val, int cap) {
int n = wgt.length;
// Initialize the dp table
int[][] dp = new int[n + 1][cap + 1];
// State transitions
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If item i exceeds the remaining capacity, do not choose it
dp[i][c] = dp[i - 1][c];
} else {
// Take the larger value obtained by excluding and including item i
dp[i][c] = Math.max(dp[i - 1][c], dp[i][c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[n][cap];
}
/* Unbounded knapsack: dynamic programming */
int UnboundedKnapsackDP(int[] wgt, int[] val, int cap) {
int n = wgt.Length;
// Initialize the dp table
int[,] dp = new int[n + 1, cap + 1];
// State transitions
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If item i exceeds the remaining capacity, do not choose it
dp[i, c] = dp[i - 1, c];
} else {
// Take the larger value obtained by excluding and including item i
dp[i, c] = Math.Max(dp[i - 1, c], dp[i, c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[n, cap];
}
/* Unbounded knapsack: dynamic programming */
func unboundedKnapsackDP(wgt, val []int, cap int) int {
n := len(wgt)
// Initialize the dp table
dp := make([][]int, n+1)
for i := 0; i <= n; i++ {
dp[i] = make([]int, cap+1)
}
// State transitions
for i := 1; i <= n; i++ {
for c := 1; c <= cap; c++ {
if wgt[i-1] > c {
// If item i exceeds the remaining capacity, do not choose it
dp[i][c] = dp[i-1][c]
} else {
// Take the larger value obtained by excluding and including item i
dp[i][c] = int(math.Max(float64(dp[i-1][c]), float64(dp[i][c-wgt[i-1]]+val[i-1])))
}
}
}
return dp[n][cap]
}
/* Unbounded knapsack: dynamic programming */
func unboundedKnapsackDP(wgt: [Int], val: [Int], cap: Int) -> Int {
let n = wgt.count
// Initialize the dp table
var dp = Array(repeating: Array(repeating: 0, count: cap + 1), count: n + 1)
// State transitions
for i in 1 ... n {
for c in 1 ... cap {
if wgt[i - 1] > c {
// If item i exceeds the remaining capacity, do not choose it
dp[i][c] = dp[i - 1][c]
} else {
// Take the larger value obtained by excluding and including item i
dp[i][c] = max(dp[i - 1][c], dp[i][c - wgt[i - 1]] + val[i - 1])
}
}
}
return dp[n][cap]
}
/* Unbounded knapsack: dynamic programming */
function unboundedKnapsackDP(wgt, val, cap) {
const n = wgt.length;
// Initialize the dp table
const dp = Array.from({ length: n + 1 }, () =>
Array.from({ length: cap + 1 }, () => 0)
);
// State transitions
for (let i = 1; i <= n; i++) {
for (let c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If item i exceeds the remaining capacity, do not choose it
dp[i][c] = dp[i - 1][c];
} else {
// Take the larger value obtained by excluding and including item i
dp[i][c] = Math.max(
dp[i - 1][c],
dp[i][c - wgt[i - 1]] + val[i - 1]
);
}
}
}
return dp[n][cap];
}
/* Unbounded knapsack: dynamic programming */
function unboundedKnapsackDP(
wgt: Array<number>,
val: Array<number>,
cap: number
): number {
const n = wgt.length;
// Initialize the dp table
const dp = Array.from({ length: n + 1 }, () =>
Array.from({ length: cap + 1 }, () => 0)
);
// State transitions
for (let i = 1; i <= n; i++) {
for (let c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If item i exceeds the remaining capacity, do not choose it
dp[i][c] = dp[i - 1][c];
} else {
// Take the larger value obtained by excluding and including item i
dp[i][c] = Math.max(
dp[i - 1][c],
dp[i][c - wgt[i - 1]] + val[i - 1]
);
}
}
}
return dp[n][cap];
}
/* Unbounded knapsack: dynamic programming */
int unboundedKnapsackDP(List<int> wgt, List<int> val, int cap) {
int n = wgt.length;
// Initialize the dp table
List<List<int>> dp = List.generate(n + 1, (index) => List.filled(cap + 1, 0));
// State transitions
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If item i exceeds the remaining capacity, do not choose it
dp[i][c] = dp[i - 1][c];
} else {
// Take the larger value obtained by excluding and including item i
dp[i][c] = max(dp[i - 1][c], dp[i][c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[n][cap];
}
/* Unbounded knapsack: dynamic programming */
fn unbounded_knapsack_dp(wgt: &[i32], val: &[i32], cap: usize) -> i32 {
let n = wgt.len();
// Initialize the dp table
let mut dp = vec![vec![0; cap + 1]; n + 1];
// State transitions
for i in 1..=n {
for c in 1..=cap {
if wgt[i - 1] > c as i32 {
// If item i exceeds the remaining capacity, do not choose it
dp[i][c] = dp[i - 1][c];
} else {
// Take the larger value obtained by excluding and including item i
dp[i][c] = std::cmp::max(dp[i - 1][c], dp[i][c - wgt[i - 1] as usize] + val[i - 1]);
}
}
}
return dp[n][cap];
}
/* Unbounded knapsack: dynamic programming */
int unboundedKnapsackDP(int wgt[], int val[], int cap, int wgtSize) {
int n = wgtSize;
// Initialize the dp table
int **dp = malloc((n + 1) * sizeof(int *));
for (int i = 0; i <= n; i++) {
dp[i] = calloc(cap + 1, sizeof(int));
}
// State transitions
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If item i exceeds the remaining capacity, do not choose it
dp[i][c] = dp[i - 1][c];
} else {
// Take the larger value obtained by excluding and including item i
dp[i][c] = myMax(dp[i - 1][c], dp[i][c - wgt[i - 1]] + val[i - 1]);
}
}
}
int res = dp[n][cap];
// Free memory
for (int i = 0; i <= n; i++) {
free(dp[i]);
}
return res;
}
/* Unbounded knapsack: dynamic programming */
fun unboundedKnapsackDP(wgt: IntArray, _val: IntArray, cap: Int): Int {
val n = wgt.size
// Initialize the dp table
val dp = Array(n + 1) { IntArray(cap + 1) }
// State transitions
for (i in 1..n) {
for (c in 1..cap) {
if (wgt[i - 1] > c) {
// If item i exceeds the remaining capacity, do not choose it
dp[i][c] = dp[i - 1][c]
} else {
// Take the larger value obtained by excluding and including item i
dp[i][c] = max(dp[i - 1][c], dp[i][c - wgt[i - 1]] + _val[i - 1])
}
}
}
return dp[n][cap]
}
### Unbounded knapsack: dynamic programming ###
def unbounded_knapsack_dp(wgt, val, cap)
n = wgt.length
# Initialize the dp table
dp = Array.new(n + 1) { Array.new(cap + 1, 0) }
# State transitions
for i in 1...(n + 1)
for c in 1...(cap + 1)
if wgt[i - 1] > c
# If item i exceeds the remaining capacity, do not choose it
dp[i][c] = dp[i - 1][c]
else
# Take the larger value obtained by excluding and including item i
dp[i][c] = [dp[i - 1][c], dp[i][c - wgt[i - 1]] + val[i - 1]].max
end
end
end
dp[n][cap]
end
Visualize execution
3. Space optimization¶
The current state depends on states to its left and above, so after space optimization, each row of the \(dp\) table must be processed in forward order.
This is the opposite of 0-1 knapsack. Use Figure 14-23 to understand the difference.
Figure 14-23 Space-optimized dynamic programming for unbounded knapsack
Description of Figure 14-23: Single-row update for unbounded knapsack
Update the single-row array in forward order of increasing capacity, reusing the current round's updated solutions at smaller capacities so the same item can be chosen repeatedly.
The knapsack capacity limit is 4, and all three items may be chosen repeatedly; see the "Item inputs for forward-order unbounded knapsack updates" table below for their exact weights and values. Starting after item 1 (apple) has been processed, this example demonstrates only the round for item 2 (pineapple), while item 3 (watermelon) has not yet participated.
The two-dimensional state dp[i, c] represents the maximum value achievable using only the first i items with total weight not exceeding capacity c; after space optimization, the single-row array dp[c] (for capacity index c from 0 to 4) overwrites the previous round's results round by round.
Round i = 2 traverses capacities c = 1, 2, 3, 4 in forward order. When capacity is too small to fit a pineapple (c < 2), the old value from the previous round is retained; when it fits (c >= 2), the old value dp[c] (excluding the pineapple) is compared against the current-round value dp[c - 2] + 11 (including a pineapple), and the larger value is written to dp[c]. Because smaller positive capacities have already been processed in this round and capacity 0 always remains the valid boundary value 0, reading dp[c - 2] from the left within the same row in forward order allows another pineapple to be added, enabling repeated selection of the same item; the 0-1 knapsack restriction—where each item can be used at most once and old values from the previous round must be read in reverse order—does not apply here.
The upper part of the figure shows the two-dimensional table and the lower part shows the single-row array; at each step, the transcript presents the complete state as the single-row table followed by the two-dimensional reference table, with the step number included in both table captions. The single-row table has separate columns for each value and the round that produced it: i = 1 means only apples may be chosen, and i = 2 means apples and pineapples may be chosen, without implying that a solution must include both. Blue indicates states from the previous round, and green indicates entries already processed in the current round; at the end of the round, the current round's results turn blue uniformly to serve as the old states for the next round. In the two-dimensional table, a 0 marked "uncomputed initial value" must not be treated as a computed solution.
| ID i | Item | Weight | Value |
|---|---|---|---|
| 1 | Apple | 1 | 5 |
| 2 | Pineapple | 2 | 11 |
| 3 | Watermelon | 3 | 15 |
Before traversing i = 2: single row stores the i = 1 solutions
Before round i = 2 (pineapple) begins, round 1 (only apples available) has already been computed: because apples may be chosen repeatedly, capacities 0 through 4 pack 0 through 4 apples for maximum values of [0, 5, 10, 15, 20]. The single-row array dp currently holds these i = 1 solutions and is ready to process item 2 (pineapple) from left to right in forward order.
Unbounded knapsack step 1: Before traversing i = 2, single row stores the i = 1 solutions — single-row dp values and round ownership Capacity c Current value Round and available items 0 0 Capacity 0 boundary shared across rounds 1 5 Previous round i = 1, only apples available, not yet overwritten 2 10 Previous round i = 1, only apples available, not yet overwritten 3 15 Previous round i = 1, only apples available, not yet overwritten 4 20 Previous round i = 1, only apples available, not yet overwritten Unbounded knapsack step 1: Before traversing i = 2, single row stores the i = 1 solutions — two-dimensional reference table of subproblem progress Available items Capacity 0 Capacity 1 Capacity 2 Capacity 3 Capacity 4 First 0 items 0, valid boundary 0, valid boundary 0, valid boundary 0, valid boundary 0, valid boundary First 1 item 0, valid boundary 5, computed 10, computed 15, computed 20, computed First 2 items 0, valid boundary 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value First 3 items 0, valid boundary 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Process capacity c = 1 in forward order: pineapple does not fit, keep 5
Start forward-order traversal at capacity c = 1: a pineapple weighs 2, which exceeds capacity 1, so it cannot fit. In the two-dimensional reference table, dp[2, 1] inherits dp[1, 1] = 5 directly from above; in the single-row array, dp[1] keeps the value 5, but now represents the current round i = 2 (highlighted in green in the figure as processed in this round), whereas capacities 2 through 4 remain old values from round i = 1.
Unbounded knapsack step 2: Process capacity c = 1 in forward order (pineapple does not fit, keep 5) — single-row dp values and round ownership Capacity c Current value Round and available items 0 0 Capacity 0 boundary shared across rounds 1 5 Current round i = 2, available items: apple, pineapple 2 10 Previous round i = 1, only apples available, not yet overwritten 3 15 Previous round i = 1, only apples available, not yet overwritten 4 20 Previous round i = 1, only apples available, not yet overwritten Unbounded knapsack step 2: Process capacity c = 1 in forward order (pineapple does not fit, keep 5) — two-dimensional reference table of subproblem progress Available items Capacity 0 Capacity 1 Capacity 2 Capacity 3 Capacity 4 First 0 items 0, valid boundary 0, valid boundary 0, valid boundary 0, valid boundary 0, valid boundary First 1 item 0, valid boundary 5, computed 10, computed 15, computed 20, computed First 2 items 0, valid boundary 5, computed 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value First 3 items 0, valid boundary 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Update capacity c = 2 in forward order: include 1 pineapple, update to 11
Advance rightward in forward order to capacity c = 2: excluding the pineapple keeps the previous round's old value dp[2] = 10 (two apples); including 1 pineapple reads the capacity 0 boundary state dp[0] = 0 to the left in the same row and adds pineapple value 11 to get 11. Taking max(10, 11) = 11 updates single-row dp[2] to the new current-round value 11.
Unbounded knapsack step 3: Update capacity c = 2 in forward order (include 1 pineapple, update to 11) — single-row dp values and round ownership Capacity c Current value Round and available items 0 0 Capacity 0 boundary shared across rounds 1 5 Current round i = 2, available items: apple, pineapple 2 11 Current round i = 2, available items: apple, pineapple 3 15 Previous round i = 1, only apples available, not yet overwritten 4 20 Previous round i = 1, only apples available, not yet overwritten Unbounded knapsack step 3: Update capacity c = 2 in forward order (include 1 pineapple, update to 11) — two-dimensional reference table of subproblem progress Available items Capacity 0 Capacity 1 Capacity 2 Capacity 3 Capacity 4 First 0 items 0, valid boundary 0, valid boundary 0, valid boundary 0, valid boundary 0, valid boundary First 1 item 0, valid boundary 5, computed 10, computed 15, computed 20, computed First 2 items 0, valid boundary 5, computed 11, computed 0, uncomputed initial value 0, uncomputed initial value First 3 items 0, valid boundary 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Update capacity c = 3 in forward order: apple plus pineapple, update to 16
Continue in forward order to capacity c = 3: excluding the pineapple gives the previous round's old value dp[3] = 15 (three apples); including 1 pineapple reads dp[1] = 5 (one apple), already processed in this round to the left in the same row, and adds pineapple value 11 to get 16 (one apple plus one pineapple). Taking max(15, 16) = 16 updates dp[3] to 16.
Unbounded knapsack step 4: Update capacity c = 3 in forward order (apple plus pineapple, update to 16) — single-row dp values and round ownership Capacity c Current value Round and available items 0 0 Capacity 0 boundary shared across rounds 1 5 Current round i = 2, available items: apple, pineapple 2 11 Current round i = 2, available items: apple, pineapple 3 16 Current round i = 2, available items: apple, pineapple 4 20 Previous round i = 1, only apples available, not yet overwritten Unbounded knapsack step 4: Update capacity c = 3 in forward order (apple plus pineapple, update to 16) — two-dimensional reference table of subproblem progress Available items Capacity 0 Capacity 1 Capacity 2 Capacity 3 Capacity 4 First 0 items 0, valid boundary 0, valid boundary 0, valid boundary 0, valid boundary 0, valid boundary First 1 item 0, valid boundary 5, computed 10, computed 15, computed 20, computed First 2 items 0, valid boundary 5, computed 11, computed 16, computed 0, uncomputed initial value First 3 items 0, valid boundary 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Update capacity c = 4 in forward order: reuse updated current-round value to pick pineapple twice for 22
Advance in forward order to capacity c = 4: excluding the pineapple gives the previous round's old value dp[4] = 20 (four apples); including a pineapple reads dp[2] = 11 (already containing 1 pineapple), just updated in this round to the left in the same row, and adds 1 more pineapple of value 11 to get 22 (two pineapples in total). Writing max(20, 22) = 22 into dp[4] directly illustrates how forward-order traversal reuses current-round solutions to choose the same item repeatedly.
Unbounded knapsack step 5: Update capacity c = 4 in forward order (reuse updated current-round value to pick pineapple twice for 22) — single-row dp values and round ownership Capacity c Current value Round and available items 0 0 Capacity 0 boundary shared across rounds 1 5 Current round i = 2, available items: apple, pineapple 2 11 Current round i = 2, available items: apple, pineapple 3 16 Current round i = 2, available items: apple, pineapple 4 22 Current round i = 2, available items: apple, pineapple Unbounded knapsack step 5: Update capacity c = 4 in forward order (reuse updated current-round value to pick pineapple twice for 22) — two-dimensional reference table of subproblem progress Available items Capacity 0 Capacity 1 Capacity 2 Capacity 3 Capacity 4 First 0 items 0, valid boundary 0, valid boundary 0, valid boundary 0, valid boundary 0, valid boundary First 1 item 0, valid boundary 5, computed 10, computed 15, computed 20, computed First 2 items 0, valid boundary 5, computed 11, computed 16, computed 22, computed First 3 items 0, valid boundary 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Finish round i = 2 traversal: single row stores solutions for the first two items
Forward-order traversal for round i = 2 is complete, and single-row dp = [0, 5, 11, 16, 22] stores the maximum values for capacities 0 through 4 when choosing from the first two items. This step changes no numbers and simply recolors the current round's results uniformly blue to serve as the old states for the next round. In the "First 3 items" row of the two-dimensional reference table, the 0 entries at capacities 1 through 4 remain uncomputed initial values while capacity 0 keeps boundary value 0; watermelon has not yet been processed.
Unbounded knapsack step 6: Finish round i = 2 traversal (single row stores solutions for the first two items) — single-row dp values and round ownership Capacity c Current value Round and available items 0 0 Capacity 0 boundary shared across rounds 1 5 Current round i = 2, available items: apple, pineapple; will serve as old state for next round 2 11 Current round i = 2, available items: apple, pineapple; will serve as old state for next round 3 16 Current round i = 2, available items: apple, pineapple; will serve as old state for next round 4 22 Current round i = 2, available items: apple, pineapple; will serve as old state for next round Unbounded knapsack step 6: Finish round i = 2 traversal (single row stores solutions for the first two items) — two-dimensional reference table of subproblem progress Available items Capacity 0 Capacity 1 Capacity 2 Capacity 3 Capacity 4 First 0 items 0, valid boundary 0, valid boundary 0, valid boundary 0, valid boundary 0, valid boundary First 1 item 0, valid boundary 5, computed 10, computed 15, computed 20, computed First 2 items 0, valid boundary 5, computed 11, computed 16, computed 22, computed First 3 items 0, valid boundary 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value
As an additional comparison using this example's inputs: if reverse order were used by mistake, capacity 4 would be processed before capacity 2 and could only read the old value dp[2] = 10, yielding max(20, 10 + 11) = 21 and missing 22 from two pineapples. Derived from this example's initial array rather than drawn in the figure, this counterexample shows why unbounded knapsack must traverse in forward order to reuse updated values from the current round.
The implementation simply removes the first dimension of dp:
def unbounded_knapsack_dp_comp(wgt: list[int], val: list[int], cap: int) -> int:
"""Unbounded knapsack: space-optimized dynamic programming"""
n = len(wgt)
# Initialize the dp table
dp = [0] * (cap + 1)
# State transitions
for i in range(1, n + 1):
# Traverse in increasing order
for c in range(1, cap + 1):
if wgt[i - 1] > c:
# If item i exceeds the remaining capacity, do not choose it
dp[c] = dp[c]
else:
# Take the larger value obtained by excluding and including item i
dp[c] = max(dp[c], dp[c - wgt[i - 1]] + val[i - 1])
return dp[cap]
/* Unbounded knapsack: space-optimized dynamic programming */
int unboundedKnapsackDPComp(vector<int> &wgt, vector<int> &val, int cap) {
int n = wgt.size();
// Initialize the dp table
vector<int> dp(cap + 1, 0);
// State transitions
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If item i exceeds the remaining capacity, do not choose it
dp[c] = dp[c];
} else {
// Take the larger value obtained by excluding and including item i
dp[c] = max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[cap];
}
/* Unbounded knapsack: space-optimized dynamic programming */
int unboundedKnapsackDPComp(int[] wgt, int[] val, int cap) {
int n = wgt.length;
// Initialize the dp table
int[] dp = new int[cap + 1];
// State transitions
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If item i exceeds the remaining capacity, do not choose it
dp[c] = dp[c];
} else {
// Take the larger value obtained by excluding and including item i
dp[c] = Math.max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[cap];
}
/* Unbounded knapsack: space-optimized dynamic programming */
int UnboundedKnapsackDPComp(int[] wgt, int[] val, int cap) {
int n = wgt.Length;
// Initialize the dp table
int[] dp = new int[cap + 1];
// State transitions
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If item i exceeds the remaining capacity, do not choose it
dp[c] = dp[c];
} else {
// Take the larger value obtained by excluding and including item i
dp[c] = Math.Max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[cap];
}
/* Unbounded knapsack: space-optimized dynamic programming */
func unboundedKnapsackDPComp(wgt, val []int, cap int) int {
n := len(wgt)
// Initialize the dp table
dp := make([]int, cap+1)
// State transitions
for i := 1; i <= n; i++ {
for c := 1; c <= cap; c++ {
if wgt[i-1] > c {
// If item i exceeds the remaining capacity, do not choose it
dp[c] = dp[c]
} else {
// Take the larger value obtained by excluding and including item i
dp[c] = int(math.Max(float64(dp[c]), float64(dp[c-wgt[i-1]]+val[i-1])))
}
}
}
return dp[cap]
}
/* Unbounded knapsack: space-optimized dynamic programming */
func unboundedKnapsackDPComp(wgt: [Int], val: [Int], cap: Int) -> Int {
let n = wgt.count
// Initialize the dp table
var dp = Array(repeating: 0, count: cap + 1)
// State transitions
for i in 1 ... n {
for c in 1 ... cap {
if wgt[i - 1] > c {
// If item i exceeds the remaining capacity, do not choose it
dp[c] = dp[c]
} else {
// Take the larger value obtained by excluding and including item i
dp[c] = max(dp[c], dp[c - wgt[i - 1]] + val[i - 1])
}
}
}
return dp[cap]
}
/* Unbounded knapsack: space-optimized dynamic programming */
function unboundedKnapsackDPComp(wgt, val, cap) {
const n = wgt.length;
// Initialize the dp table
const dp = Array.from({ length: cap + 1 }, () => 0);
// State transitions
for (let i = 1; i <= n; i++) {
for (let c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If item i exceeds the remaining capacity, do not choose it
dp[c] = dp[c];
} else {
// Take the larger value obtained by excluding and including item i
dp[c] = Math.max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[cap];
}
/* Unbounded knapsack: space-optimized dynamic programming */
function unboundedKnapsackDPComp(
wgt: Array<number>,
val: Array<number>,
cap: number
): number {
const n = wgt.length;
// Initialize the dp table
const dp = Array.from({ length: cap + 1 }, () => 0);
// State transitions
for (let i = 1; i <= n; i++) {
for (let c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If item i exceeds the remaining capacity, do not choose it
dp[c] = dp[c];
} else {
// Take the larger value obtained by excluding and including item i
dp[c] = Math.max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[cap];
}
/* Unbounded knapsack: space-optimized dynamic programming */
int unboundedKnapsackDPComp(List<int> wgt, List<int> val, int cap) {
int n = wgt.length;
// Initialize the dp table
List<int> dp = List.filled(cap + 1, 0);
// State transitions
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If item i exceeds the remaining capacity, do not choose it
dp[c] = dp[c];
} else {
// Take the larger value obtained by excluding and including item i
dp[c] = max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[cap];
}
/* Unbounded knapsack: space-optimized dynamic programming */
fn unbounded_knapsack_dp_comp(wgt: &[i32], val: &[i32], cap: usize) -> i32 {
let n = wgt.len();
// Initialize the dp table
let mut dp = vec![0; cap + 1];
// State transitions
for i in 1..=n {
for c in 1..=cap {
if wgt[i - 1] > c as i32 {
// If item i exceeds the remaining capacity, do not choose it
dp[c] = dp[c];
} else {
// Take the larger value obtained by excluding and including item i
dp[c] = std::cmp::max(dp[c], dp[c - wgt[i - 1] as usize] + val[i - 1]);
}
}
}
dp[cap]
}
/* Unbounded knapsack: space-optimized dynamic programming */
int unboundedKnapsackDPComp(int wgt[], int val[], int cap, int wgtSize) {
int n = wgtSize;
// Initialize the dp table
int *dp = calloc(cap + 1, sizeof(int));
// State transitions
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// If item i exceeds the remaining capacity, do not choose it
dp[c] = dp[c];
} else {
// Take the larger value obtained by excluding and including item i
dp[c] = myMax(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
}
}
}
int res = dp[cap];
// Free memory
free(dp);
return res;
}
/* Unbounded knapsack: space-optimized dynamic programming */
fun unboundedKnapsackDPComp(
wgt: IntArray,
_val: IntArray,
cap: Int
): Int {
val n = wgt.size
// Initialize the dp table
val dp = IntArray(cap + 1)
// State transitions
for (i in 1..n) {
for (c in 1..cap) {
if (wgt[i - 1] > c) {
// If item i exceeds the remaining capacity, do not choose it
dp[c] = dp[c]
} else {
// Take the larger value obtained by excluding and including item i
dp[c] = max(dp[c], dp[c - wgt[i - 1]] + _val[i - 1])
}
}
}
return dp[cap]
}
### Unbounded knapsack: space-optimized dynamic programming ###
def unbounded_knapsack_dp_comp(wgt, val, cap)
n = wgt.length
# Initialize the dp table
dp = Array.new(cap + 1, 0)
# State transitions
for i in 1...(n + 1)
# Traverse in increasing order
for c in 1...(cap + 1)
if wgt[i -1] > c
# If item i exceeds the remaining capacity, do not choose it
dp[c] = dp[c]
else
# Take the larger value obtained by excluding and including item i
dp[c] = [dp[c], dp[c - wgt[i - 1]] + val[i - 1]].max
end
end
end
dp[cap]
end
Visualize execution
14.5.2 Coin change problem¶
Knapsack represents a broad family of dynamic programming problems, with many variants such as coin change.
Question
Given \(n\) coin denominations, where denomination \(i\) has value \(coins[i - 1]\), and a target amount \(amt\), each denomination may be used repeatedly. What is the minimum number of coins needed to make the target? Return \(-1\) if it cannot be made. An example is shown in Figure 14-24.
Figure 14-24 Example input for coin change
Description of Figure 14-24: Minimum coin count for coin change
Illustrate an optimal coin selection that makes target amount 11.
Coin change provides 3 coin denominations coins = [1, 2, 5] in unlimited supply; here the target amount is amt = 11 (distinct from target amount 5 in Coin change II below and target amount 4 in the dynamic programming table). The goal is to find the minimum number of coins that sum to 11.
On the left, a table lists ID i and denomination coins[i - 1]; denomination 1 is shaded light orange and denomination 5 is shaded light green, sending arrows for 1 coin and 2 coins into the pouch on the right labeled "Target amount amt = 11". Denomination 2 is unused. The table below summarizes these highlights and arrows as coin counts.
At the bottom appear "Optimal coin combination: 1 + 5 + 5" and "Minimum number of coins: 3".
| ID i | Denomination | Coins used in figure |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 2 | 0 |
| 3 | 5 | 2 |
From the illustrated combination, 1 + 5 + 5 = 11 using 3 coins in total. Why 3 is minimal: because the largest denomination is 5, any two coins sum to at most 5 + 5 = 10 < 11, so fewer than 3 coins cannot reach 11 (derived from the input data rather than written in the figure).
1. Dynamic programming approach¶
Coin change can be viewed as a special case of unbounded knapsack, with the following connections and differences.
- The two problems can be translated into one another: items correspond to coins, item weights to coin denominations, and knapsack capacity to the target amount.
- The optimization objectives are opposite: unbounded knapsack maximizes item value, while coin change minimizes the number of coins.
- Unbounded knapsack must stay within a capacity limit, whereas coin change must reach the target amount exactly.
Step 1: Identify each decision, define the state, and establish the \(dp\) table
State \([i, a]\) represents the subproblem of finding the minimum number of coins needed to make amount \(a\) using the first \(i\) denominations, denoted by \(dp[i, a]\).
The two-dimensional \(dp\) table has size \((n+1) \times (amt+1)\).
Step 2: Identify optimal substructure and derive the state transition equation
The state transition differs from unbounded knapsack in two ways.
- We want a minimum, so replace \(\max()\) with \(\min()\).
- We optimize the coin count rather than item value, so choosing a coin adds \(+1\).
Step 3: Determine the boundary conditions and evaluation order
A target amount of \(0\) requires \(0\) coins, so every entry \(dp[i, 0]\) in the first column is \(0\).
With no coins, any target amount \(> 0\) is impossible. To let \(\min()\) recognize and discard these infeasible solutions, represent them by \(+ \infty\): set the first-row entries \(dp[0, a]\) to \(+ \infty\).
2. Code implementation¶
Most programming languages do not provide an integer value for \(+ \infty\), so the maximum int value is used instead. However, the \(+ 1\) in the transition may then overflow.
Instead, use \(amt + 1\) to represent an infeasible solution, since making \(amt\) requires at most \(amt\) coins. Before returning, check whether \(dp[n, amt]\) equals \(amt + 1\). If so, return \(-1\) to indicate that the target cannot be made. The code is as follows:
def coin_change_dp(coins: list[int], amt: int) -> int:
"""Coin change: dynamic programming"""
n = len(coins)
MAX = amt + 1
# Initialize the dp table
dp = [[0] * (amt + 1) for _ in range(n + 1)]
# State transitions: first row and first column
for a in range(1, amt + 1):
dp[0][a] = MAX
# State transitions: remaining rows and columns
for i in range(1, n + 1):
for a in range(1, amt + 1):
if coins[i - 1] > a:
# If the coin value exceeds the current amount a, do not choose coin i
dp[i][a] = dp[i - 1][a]
else:
# Take the smaller result of not choosing and choosing coin i
dp[i][a] = min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1)
return dp[n][amt] if dp[n][amt] != MAX else -1
/* Coin change: dynamic programming */
int coinChangeDP(vector<int> &coins, int amt) {
int n = coins.size();
int MAX = amt + 1;
// Initialize the dp table
vector<vector<int>> dp(n + 1, vector<int>(amt + 1, 0));
// State transitions: first row and first column
for (int a = 1; a <= amt; a++) {
dp[0][a] = MAX;
}
// State transitions: remaining rows and columns
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[i][a] = dp[i - 1][a];
} else {
// Take the smaller result of not choosing and choosing coin i
dp[i][a] = min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1);
}
}
}
return dp[n][amt] != MAX ? dp[n][amt] : -1;
}
/* Coin change: dynamic programming */
int coinChangeDP(int[] coins, int amt) {
int n = coins.length;
int MAX = amt + 1;
// Initialize the dp table
int[][] dp = new int[n + 1][amt + 1];
// State transitions: first row and first column
for (int a = 1; a <= amt; a++) {
dp[0][a] = MAX;
}
// State transitions: remaining rows and columns
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[i][a] = dp[i - 1][a];
} else {
// Take the smaller result of not choosing and choosing coin i
dp[i][a] = Math.min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1);
}
}
}
return dp[n][amt] != MAX ? dp[n][amt] : -1;
}
/* Coin change: dynamic programming */
int CoinChangeDP(int[] coins, int amt) {
int n = coins.Length;
int MAX = amt + 1;
// Initialize the dp table
int[,] dp = new int[n + 1, amt + 1];
// State transitions: first row and first column
for (int a = 1; a <= amt; a++) {
dp[0, a] = MAX;
}
// State transitions: remaining rows and columns
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[i, a] = dp[i - 1, a];
} else {
// Take the smaller result of not choosing and choosing coin i
dp[i, a] = Math.Min(dp[i - 1, a], dp[i, a - coins[i - 1]] + 1);
}
}
}
return dp[n, amt] != MAX ? dp[n, amt] : -1;
}
/* Coin change: dynamic programming */
func coinChangeDP(coins []int, amt int) int {
n := len(coins)
max := amt + 1
// Initialize the dp table
dp := make([][]int, n+1)
for i := 0; i <= n; i++ {
dp[i] = make([]int, amt+1)
}
// State transitions: first row and first column
for a := 1; a <= amt; a++ {
dp[0][a] = max
}
// State transitions: remaining rows and columns
for i := 1; i <= n; i++ {
for a := 1; a <= amt; a++ {
if coins[i-1] > a {
// If the coin exceeds the current target amount a, do not choose coin i
dp[i][a] = dp[i-1][a]
} else {
// Take the smaller result of not choosing and choosing coin i
dp[i][a] = int(math.Min(float64(dp[i-1][a]), float64(dp[i][a-coins[i-1]]+1)))
}
}
}
if dp[n][amt] != max {
return dp[n][amt]
}
return -1
}
/* Coin change: dynamic programming */
func coinChangeDP(coins: [Int], amt: Int) -> Int {
let n = coins.count
let MAX = amt + 1
// Initialize the dp table
var dp = Array(repeating: Array(repeating: 0, count: amt + 1), count: n + 1)
// State transitions: first row and first column
for a in 1 ... amt {
dp[0][a] = MAX
}
// State transitions: remaining rows and columns
for i in 1 ... n {
for a in 1 ... amt {
if coins[i - 1] > a {
// If the coin exceeds the current target amount a, do not choose coin i
dp[i][a] = dp[i - 1][a]
} else {
// Take the smaller result of not choosing and choosing coin i
dp[i][a] = min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1)
}
}
}
return dp[n][amt] != MAX ? dp[n][amt] : -1
}
/* Coin change: dynamic programming */
function coinChangeDP(coins, amt) {
const n = coins.length;
const MAX = amt + 1;
// Initialize the dp table
const dp = Array.from({ length: n + 1 }, () =>
Array.from({ length: amt + 1 }, () => 0)
);
// State transitions: first row and first column
for (let a = 1; a <= amt; a++) {
dp[0][a] = MAX;
}
// State transitions: remaining rows and columns
for (let i = 1; i <= n; i++) {
for (let a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[i][a] = dp[i - 1][a];
} else {
// Take the smaller result of not choosing and choosing coin i
dp[i][a] = Math.min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1);
}
}
}
return dp[n][amt] !== MAX ? dp[n][amt] : -1;
}
/* Coin change: dynamic programming */
function coinChangeDP(coins: Array<number>, amt: number): number {
const n = coins.length;
const MAX = amt + 1;
// Initialize the dp table
const dp = Array.from({ length: n + 1 }, () =>
Array.from({ length: amt + 1 }, () => 0)
);
// State transitions: first row and first column
for (let a = 1; a <= amt; a++) {
dp[0][a] = MAX;
}
// State transitions: remaining rows and columns
for (let i = 1; i <= n; i++) {
for (let a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[i][a] = dp[i - 1][a];
} else {
// Take the smaller result of not choosing and choosing coin i
dp[i][a] = Math.min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1);
}
}
}
return dp[n][amt] !== MAX ? dp[n][amt] : -1;
}
/* Coin change: dynamic programming */
int coinChangeDP(List<int> coins, int amt) {
int n = coins.length;
int MAX = amt + 1;
// Initialize the dp table
List<List<int>> dp = List.generate(n + 1, (index) => List.filled(amt + 1, 0));
// State transitions: first row and first column
for (int a = 1; a <= amt; a++) {
dp[0][a] = MAX;
}
// State transitions: remaining rows and columns
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the current amount a, do not choose coin i
dp[i][a] = dp[i - 1][a];
} else {
// Take the smaller result of not choosing and choosing coin i
dp[i][a] = min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1);
}
}
}
return dp[n][amt] != MAX ? dp[n][amt] : -1;
}
/* Coin change: dynamic programming */
fn coin_change_dp(coins: &[i32], amt: usize) -> i32 {
let n = coins.len();
let max = amt + 1;
// Initialize the dp table
let mut dp = vec![vec![0; amt + 1]; n + 1];
// State transitions: first row and first column
for a in 1..=amt {
dp[0][a] = max;
}
// State transitions: remaining rows and columns
for i in 1..=n {
for a in 1..=amt {
if coins[i - 1] > a as i32 {
// If the coin exceeds the target amount, do not choose coin i
dp[i][a] = dp[i - 1][a];
} else {
// Take the smaller result of not choosing and choosing coin i
dp[i][a] = std::cmp::min(dp[i - 1][a], dp[i][a - coins[i - 1] as usize] + 1);
}
}
}
if dp[n][amt] != max {
return dp[n][amt] as i32;
} else {
-1
}
}
/* Coin change: dynamic programming */
int coinChangeDP(int coins[], int amt, int coinsSize) {
int n = coinsSize;
int MAX = amt + 1;
// Initialize the dp table
int **dp = malloc((n + 1) * sizeof(int *));
for (int i = 0; i <= n; i++) {
dp[i] = calloc(amt + 1, sizeof(int));
}
// State transitions: first row and first column
for (int a = 1; a <= amt; a++) {
dp[0][a] = MAX;
}
// State transitions: remaining rows and columns
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[i][a] = dp[i - 1][a];
} else {
// Take the smaller result of not choosing and choosing coin i
dp[i][a] = myMin(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1);
}
}
}
int res = dp[n][amt] != MAX ? dp[n][amt] : -1;
// Free memory
for (int i = 0; i <= n; i++) {
free(dp[i]);
}
free(dp);
return res;
}
/* Coin change: dynamic programming */
fun coinChangeDP(coins: IntArray, amt: Int): Int {
val n = coins.size
val MAX = amt + 1
// Initialize the dp table
val dp = Array(n + 1) { IntArray(amt + 1) }
// State transitions: first row and first column
for (a in 1..amt) {
dp[0][a] = MAX
}
// State transitions: remaining rows and columns
for (i in 1..n) {
for (a in 1..amt) {
if (coins[i - 1] > a) {
// If the coin value exceeds the current amount a, do not choose coin i
dp[i][a] = dp[i - 1][a]
} else {
// Take the smaller result of not choosing and choosing coin i
dp[i][a] = min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1)
}
}
}
return if (dp[n][amt] != MAX) dp[n][amt] else -1
}
### Coin change: dynamic programming ###
def coin_change_dp(coins, amt)
n = coins.length
_MAX = amt + 1
# Initialize the dp table
dp = Array.new(n + 1) { Array.new(amt + 1, 0) }
# State transitions: first row and first column
(1...(amt + 1)).each { |a| dp[0][a] = _MAX }
# State transitions: remaining rows and columns
for i in 1...(n + 1)
for a in 1...(amt + 1)
if coins[i - 1] > a
# If the coin exceeds the current amount a, do not choose coin i
dp[i][a] = dp[i - 1][a]
else
# Take the smaller result of not choosing and choosing coin i
dp[i][a] = [dp[i - 1][a], dp[i][a - coins[i - 1]] + 1].min
end
end
end
dp[n][amt] != _MAX ? dp[n][amt] : -1
end
Visualize execution
Figure 14-25 shows dynamic programming for coin change, which closely resembles unbounded knapsack.
Figure 14-25 Dynamic programming for coin change
Description of Figure 14-25: Dynamic programming for coin change
Fill the table cell by cell across coin types and target amounts to find the minimum number of coins that make amount 4 exactly.
Available coin denominations are 1, 2, and 5 (3 coin types, each usable repeatedly), and the target amount is 4. State dp[i, a] denotes the minimum number of coins needed to make amount a using only the first i coin types; the two-dimensional dp table has 4 rows (i = 0 to 3) and 5 columns (a = 0 to 4).
Sentinel MAX = amt + 1 = 5 marks an unreachable (infeasible) amount rather than meaning 5 coins are required. Making amount 0 takes 0 coins, so the first column has boundary value 0; with no coins available (i = 0), every positive amount is unreachable.
First allocate a 4×5 all-zero table, then set positive-amount cells dp[0, 1] through dp[0, 4] in the first row to unreachable sentinel MAX = 5 while keeping first-column cells dp[0, 0] through dp[3, 0] at valid boundary 0. Next fill rows i = 1 to 3 across amounts a = 1 to 4: when the current denomination exceeds a, it cannot be used, so inherit dp[i - 1, a] directly above; otherwise compare dp[i - 1, a] above (excluding this coin) with dp[i, a - coins[i - 1]] + 1 to the left in the same row (including one coin of this denomination) and take the smaller value. Reading from the left within the same row allows using the same denomination repeatedly.
Each step includes the complete dp state table whose caption names the step number and action, with row headers showing i and available denominations and column headers showing amounts. First-column cells are marked "boundary set", first-row infeasible cells are marked "MAX, unreachable boundary", cells settled in earlier steps are marked "computed", and unevaluated cells are marked "uncomputed initial value" and must not be read as solved coin counts. Newly written cells are marked "written in this step", and Step 15 marks the bottom-right cell "return value" and displays all final entries.
| ID i | Denomination |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 5 |
Allocate the initial 4×5 all-zero dp table
For 3 coin types (denominations 1, 2, 5) and target amount 4, allocate a 4×5 two-dimensional dp table (rows i = 0 to 3, columns a = 0 to 4). Initially every cell defaults to 0: column 0 (amount 0) already holds its valid boundary 0 (0 coins make amount 0), whereas 0 in every positive-amount cell is an uncomputed initial value awaiting Step 2 to set first-row unreachable sentinel MAX.
Coin change step 1: full dp table after allocating all-zero table (MAX = 5, unreachable) First i coin types and denominations Amount 0 Amount 1 Amount 2 Amount 3 Amount 4 i = 0, no coins 0, boundary set 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value i = 1, denomination 1 0, boundary set 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value i = 2, denominations 1, 2 0, boundary set 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value i = 3, denominations 1, 2, 5 0, boundary set 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Set positive amounts in row 0 to unreachable boundary MAX = 5
With no coins available (i = 0), no positive amount can be made, so set first-row positive cells dp[0, 1] through dp[0, 4] to unreachable sentinel MAX = 5 (marking infeasibility rather than 5 coins); amount a = 0 requires 0 coins, so first-column cells dp[0, 0] through dp[3, 0] stay at boundary 0. Positive-amount zeros in rows 1 to 3 remain uncomputed initial values.
Coin change step 2: full dp table after boundary initialization (MAX = 5, unreachable) First i coin types and denominations Amount 0 Amount 1 Amount 2 Amount 3 Amount 4 i = 0, no coins 0, boundary set MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary i = 1, denomination 1 0, boundary set 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value i = 2, denominations 1, 2 0, boundary set 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value i = 3, denominations 1, 2, 5 0, boundary set 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Compute dp[1, 1] (denomination 1, amount 1): minimum 1 coin
Begin coin type 1 (denomination 1) at amount a = 1 for dp[1, 1]: excluding denomination 1 gives upper dp[0, 1] = MAX (5, unreachable); including 1 coin of denomination 1 takes same-row left boundary dp[1, 0] = 0 plus 1 to get 1. Write the smaller value min(MAX, 1) = 1 to dp[1, 1], corresponding to 1 coin of denomination 1.
Coin change step 3: full dp table after computing dp[1, 1] (MAX = 5, unreachable) First i coin types and denominations Amount 0 Amount 1 Amount 2 Amount 3 Amount 4 i = 0, no coins 0, boundary set MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary i = 1, denomination 1 0, boundary set 1, written in this step 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value i = 2, denominations 1, 2 0, boundary set 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value i = 3, denominations 1, 2, 5 0, boundary set 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Compute dp[1, 2] (denomination 1, amount 2): minimum 2 coins
Continue with coin type 1 (denomination 1) at amount a = 2 for dp[1, 2]: excluding it gives upper dp[0, 2] = MAX (unreachable); including 1 coin of denomination 1 reuses same-row left dp[1, 1] = 1 just computed plus 1 to get 2 (two coins of value 1). Write min(MAX, 2) = 2 to dp[1, 2].
Coin change step 4: full dp table after computing dp[1, 2] (MAX = 5, unreachable) First i coin types and denominations Amount 0 Amount 1 Amount 2 Amount 3 Amount 4 i = 0, no coins 0, boundary set MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary i = 1, denomination 1 0, boundary set 1, computed 2, written in this step 0, uncomputed initial value 0, uncomputed initial value i = 2, denominations 1, 2 0, boundary set 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value i = 3, denominations 1, 2, 5 0, boundary set 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Compute dp[1, 3] (denomination 1, amount 3): minimum 3 coins
Continue with coin type 1 (denomination 1) at amount a = 3 for dp[1, 3]: excluding it gives upper dp[0, 3] = MAX (unreachable); including 1 coin of denomination 1 takes same-row left dp[1, 2] = 2 plus 1 to get 3 (three coins of value 1). Write min(MAX, 3) = 3 to dp[1, 3].
Coin change step 5: full dp table after computing dp[1, 3] (MAX = 5, unreachable) First i coin types and denominations Amount 0 Amount 1 Amount 2 Amount 3 Amount 4 i = 0, no coins 0, boundary set MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary i = 1, denomination 1 0, boundary set 1, computed 2, computed 3, written in this step 0, uncomputed initial value i = 2, denominations 1, 2 0, boundary set 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value i = 3, denominations 1, 2, 5 0, boundary set 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Compute dp[1, 4] (denomination 1, amount 4): minimum 4 coins
Continue with coin type 1 (denomination 1) at amount a = 4 for dp[1, 4]: excluding it gives upper dp[0, 4] = MAX (unreachable); including 1 coin of denomination 1 takes same-row left dp[1, 3] = 3 plus 1 to get 4 (four coins of value 1). Write min(MAX, 4) = 4 to dp[1, 4], completing row 1.
Coin change step 6: full dp table after computing dp[1, 4] (MAX = 5, unreachable) First i coin types and denominations Amount 0 Amount 1 Amount 2 Amount 3 Amount 4 i = 0, no coins 0, boundary set MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary i = 1, denomination 1 0, boundary set 1, computed 2, computed 3, computed 4, written in this step i = 2, denominations 1, 2 0, boundary set 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value i = 3, denominations 1, 2, 5 0, boundary set 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Compute dp[2, 1] (denomination 2, amount 1): denomination too large, inherit 1 coin
Enter row 2 to introduce coin type 2 (denomination 2) at amount a = 1 for dp[2, 1]. Because denomination 2 exceeds amount 1, a value-2 coin cannot fit, so inherit upper dp[1, 1] = 1 directly and write dp[2, 1] = 1.
Coin change step 7: full dp table after computing dp[2, 1] (MAX = 5, unreachable) First i coin types and denominations Amount 0 Amount 1 Amount 2 Amount 3 Amount 4 i = 0, no coins 0, boundary set MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary i = 1, denomination 1 0, boundary set 1, computed 2, computed 3, computed 4, computed i = 2, denominations 1, 2 0, boundary set 1, written in this step 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value i = 3, denominations 1, 2, 5 0, boundary set 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Compute dp[2, 2] (denomination 2, amount 2): take 1 coin of value 2, write 1
For coin type 2 (denomination 2) at amount a = 2: excluding value-2 coins inherits upper dp[1, 2] = 2 (two coins of value 1); including 1 coin of value 2 takes same-row left boundary dp[2, 0] = 0 plus 1 to get 1 (1 coin of value 2). Write the smaller value min(2, 1) = 1 to dp[2, 2].
Coin change step 8: full dp table after computing dp[2, 2] (MAX = 5, unreachable) First i coin types and denominations Amount 0 Amount 1 Amount 2 Amount 3 Amount 4 i = 0, no coins 0, boundary set MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary i = 1, denomination 1 0, boundary set 1, computed 2, computed 3, computed 4, computed i = 2, denominations 1, 2 0, boundary set 1, computed 1, written in this step 0, uncomputed initial value 0, uncomputed initial value i = 3, denominations 1, 2, 5 0, boundary set 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Compute dp[2, 3] (denomination 2, amount 3): 1 plus 2 uses 2 coins
For coin type 2 (denomination 2) at amount a = 3: excluding value-2 coins gives upper dp[1, 3] = 3 (three coins of value 1); including 1 coin of value 2 takes same-row left dp[2, 1] = 1 (1 coin of value 1) plus 1 to get 2 (1 coin each of values 1 and 2). Write min(3, 2) = 2 to dp[2, 3].
Coin change step 9: full dp table after computing dp[2, 3] (MAX = 5, unreachable) First i coin types and denominations Amount 0 Amount 1 Amount 2 Amount 3 Amount 4 i = 0, no coins 0, boundary set MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary i = 1, denomination 1 0, boundary set 1, computed 2, computed 3, computed 4, computed i = 2, denominations 1, 2 0, boundary set 1, computed 1, computed 2, written in this step 0, uncomputed initial value i = 3, denominations 1, 2, 5 0, boundary set 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Compute dp[2, 4] (denomination 2, amount 4): use another coin of denomination 2; write a count of 2
For coin type 2 (denomination 2) at amount a = 4: excluding value-2 coins gives upper dp[1, 4] = 4 (four coins of value 1); including a value-2 coin reuses updated same-row left dp[2, 2] = 1 (already holding 1 coin of value 2) plus 1 to get 2 (two coins of value 2). Write min(4, 2) = 2 to dp[2, 4], completing row 2 and showing how same-row left transitions allow reusing the same denomination.
Coin change step 10: full dp table after computing dp[2, 4] (MAX = 5, unreachable) First i coin types and denominations Amount 0 Amount 1 Amount 2 Amount 3 Amount 4 i = 0, no coins 0, boundary set MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary i = 1, denomination 1 0, boundary set 1, computed 2, computed 3, computed 4, computed i = 2, denominations 1, 2 0, boundary set 1, computed 1, computed 2, computed 2, written in this step i = 3, denominations 1, 2, 5 0, boundary set 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Compute dp[3, 1] (denomination 5, amount 1): denomination too large, inherit 1 coin
Enter row 3 to introduce coin type 3 (denomination 5) at amount a = 1 for dp[3, 1]. Because denomination 5 exceeds amount 1, a value-5 coin cannot fit, so inherit upper dp[2, 1] = 1 directly and write dp[3, 1] = 1.
Coin change step 11: full dp table after computing dp[3, 1] (MAX = 5, unreachable) First i coin types and denominations Amount 0 Amount 1 Amount 2 Amount 3 Amount 4 i = 0, no coins 0, boundary set MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary i = 1, denomination 1 0, boundary set 1, computed 2, computed 3, computed 4, computed i = 2, denominations 1, 2 0, boundary set 1, computed 1, computed 2, computed 2, computed i = 3, denominations 1, 2, 5 0, boundary set 1, written in this step 0, uncomputed initial value 0, uncomputed initial value 0, uncomputed initial value Compute dp[3, 2] (denomination 5, amount 2): denomination too large, inherit 1 coin
Continue with coin type 3 (denomination 5) at amount a = 2: denomination 5 still exceeds amount 2, so a value-5 coin cannot fit; inherit upper dp[2, 2] = 1 directly and write dp[3, 2] = 1.
Coin change step 12: full dp table after computing dp[3, 2] (MAX = 5, unreachable) First i coin types and denominations Amount 0 Amount 1 Amount 2 Amount 3 Amount 4 i = 0, no coins 0, boundary set MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary i = 1, denomination 1 0, boundary set 1, computed 2, computed 3, computed 4, computed i = 2, denominations 1, 2 0, boundary set 1, computed 1, computed 2, computed 2, computed i = 3, denominations 1, 2, 5 0, boundary set 1, computed 1, written in this step 0, uncomputed initial value 0, uncomputed initial value Compute dp[3, 3] (denomination 5, amount 3): denomination too large, inherit 2 coins
Continue with coin type 3 (denomination 5) at amount a = 3: denomination 5 exceeds amount 3, so a value-5 coin cannot fit; inherit upper dp[2, 3] = 2 directly and write dp[3, 3] = 2.
Coin change step 13: full dp table after computing dp[3, 3] (MAX = 5, unreachable) First i coin types and denominations Amount 0 Amount 1 Amount 2 Amount 3 Amount 4 i = 0, no coins 0, boundary set MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary i = 1, denomination 1 0, boundary set 1, computed 2, computed 3, computed 4, computed i = 2, denominations 1, 2 0, boundary set 1, computed 1, computed 2, computed 2, computed i = 3, denominations 1, 2, 5 0, boundary set 1, computed 1, computed 2, written in this step 0, uncomputed initial value Compute dp[3, 4] (denomination 5, amount 4): denomination too large, inherit 2 coins
At bottom-right target amount a = 4 for coin type 3 (denomination 5): because denomination 5 exceeds amount 4, a value-5 coin cannot fit, so inherit upper dp[2, 4] = 2 from the first two coin types (two coins of value 2 making amount 4) and write dp[3, 4] = 2, completing the table.
Coin change step 14: full dp table after computing dp[3, 4] (MAX = 5, unreachable) First i coin types and denominations Amount 0 Amount 1 Amount 2 Amount 3 Amount 4 i = 0, no coins 0, boundary set MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary i = 1, denomination 1 0, boundary set 1, computed 2, computed 3, computed 4, computed i = 2, denominations 1, 2 0, boundary set 1, computed 1, computed 2, computed 2, computed i = 3, denominations 1, 2, 5 0, boundary set 1, computed 1, computed 2, computed 2, written in this step Read bottom-right dp[3, 4] and return minimum coin count 2
With all state transitions complete, read highlighted bottom-right cell dp[3, 4] = 2. Because it differs from unreachable sentinel MAX (5), return 2 directly as the minimum number of coins needed to make amount 4 (using two coins of value 2; if it equaled MAX, -1 would be returned). No cell values change in this step.
Coin change step 15: full dp table upon returning the result (MAX = 5, unreachable) First i coin types and denominations Amount 0 Amount 1 Amount 2 Amount 3 Amount 4 i = 0, no coins 0, boundary set MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary MAX, unreachable boundary i = 1, denomination 1 0, boundary set 1, computed 2, computed 3, computed 4, computed i = 2, denominations 1, 2 0, boundary set 1, computed 1, computed 2, computed 2, computed i = 3, denominations 1, 2, 5 0, boundary set 1, computed 1, computed 2, computed 2, return value
Because denomination 5 exceeds every positive amount 1 through 4 in this table, row 3 simply inherits the two-coin-type results above it. In code, if the final entry equals MAX, -1 is returned to indicate no solution.
3. Space optimization¶
Space optimization is the same as for unbounded knapsack:
def coin_change_dp_comp(coins: list[int], amt: int) -> int:
"""Coin change: space-optimized dynamic programming"""
n = len(coins)
MAX = amt + 1
# Initialize the dp table
dp = [MAX] * (amt + 1)
dp[0] = 0
# State transitions
for i in range(1, n + 1):
# Traverse in increasing order
for a in range(1, amt + 1):
if coins[i - 1] > a:
# If the coin value exceeds the current amount a, do not choose coin i
dp[a] = dp[a]
else:
# Take the smaller result of not choosing and choosing coin i
dp[a] = min(dp[a], dp[a - coins[i - 1]] + 1)
return dp[amt] if dp[amt] != MAX else -1
/* Coin change: space-optimized dynamic programming */
int coinChangeDPComp(vector<int> &coins, int amt) {
int n = coins.size();
int MAX = amt + 1;
// Initialize the dp table
vector<int> dp(amt + 1, MAX);
dp[0] = 0;
// State transitions
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[a] = dp[a];
} else {
// Take the smaller result of not choosing and choosing coin i
dp[a] = min(dp[a], dp[a - coins[i - 1]] + 1);
}
}
}
return dp[amt] != MAX ? dp[amt] : -1;
}
/* Coin change: space-optimized dynamic programming */
int coinChangeDPComp(int[] coins, int amt) {
int n = coins.length;
int MAX = amt + 1;
// Initialize the dp table
int[] dp = new int[amt + 1];
Arrays.fill(dp, MAX);
dp[0] = 0;
// State transitions
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[a] = dp[a];
} else {
// Take the smaller result of not choosing and choosing coin i
dp[a] = Math.min(dp[a], dp[a - coins[i - 1]] + 1);
}
}
}
return dp[amt] != MAX ? dp[amt] : -1;
}
/* Coin change: space-optimized dynamic programming */
int CoinChangeDPComp(int[] coins, int amt) {
int n = coins.Length;
int MAX = amt + 1;
// Initialize the dp table
int[] dp = new int[amt + 1];
Array.Fill(dp, MAX);
dp[0] = 0;
// State transitions
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[a] = dp[a];
} else {
// Take the smaller result of not choosing and choosing coin i
dp[a] = Math.Min(dp[a], dp[a - coins[i - 1]] + 1);
}
}
}
return dp[amt] != MAX ? dp[amt] : -1;
}
/* Coin change: dynamic programming */
func coinChangeDPComp(coins []int, amt int) int {
n := len(coins)
max := amt + 1
// Initialize the dp table
dp := make([]int, amt+1)
for i := 1; i <= amt; i++ {
dp[i] = max
}
// State transitions
for i := 1; i <= n; i++ {
// Traverse in increasing order
for a := 1; a <= amt; a++ {
if coins[i-1] > a {
// If the coin exceeds the current target amount a, do not choose coin i
dp[a] = dp[a]
} else {
// Take the smaller result of not choosing and choosing coin i
dp[a] = int(math.Min(float64(dp[a]), float64(dp[a-coins[i-1]]+1)))
}
}
}
if dp[amt] != max {
return dp[amt]
}
return -1
}
/* Coin change: space-optimized dynamic programming */
func coinChangeDPComp(coins: [Int], amt: Int) -> Int {
let n = coins.count
let MAX = amt + 1
// Initialize the dp table
var dp = Array(repeating: MAX, count: amt + 1)
dp[0] = 0
// State transitions
for i in 1 ... n {
for a in 1 ... amt {
if coins[i - 1] > a {
// If the coin exceeds the current target amount a, do not choose coin i
dp[a] = dp[a]
} else {
// Take the smaller result of not choosing and choosing coin i
dp[a] = min(dp[a], dp[a - coins[i - 1]] + 1)
}
}
}
return dp[amt] != MAX ? dp[amt] : -1
}
/* Coin change: space-optimized dynamic programming */
function coinChangeDPComp(coins, amt) {
const n = coins.length;
const MAX = amt + 1;
// Initialize the dp table
const dp = Array.from({ length: amt + 1 }, () => MAX);
dp[0] = 0;
// State transitions
for (let i = 1; i <= n; i++) {
for (let a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[a] = dp[a];
} else {
// Take the smaller result of not choosing and choosing coin i
dp[a] = Math.min(dp[a], dp[a - coins[i - 1]] + 1);
}
}
}
return dp[amt] !== MAX ? dp[amt] : -1;
}
/* Coin change: space-optimized dynamic programming */
function coinChangeDPComp(coins: Array<number>, amt: number): number {
const n = coins.length;
const MAX = amt + 1;
// Initialize the dp table
const dp = Array.from({ length: amt + 1 }, () => MAX);
dp[0] = 0;
// State transitions
for (let i = 1; i <= n; i++) {
for (let a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[a] = dp[a];
} else {
// Take the smaller result of not choosing and choosing coin i
dp[a] = Math.min(dp[a], dp[a - coins[i - 1]] + 1);
}
}
}
return dp[amt] !== MAX ? dp[amt] : -1;
}
/* Coin change: space-optimized dynamic programming */
int coinChangeDPComp(List<int> coins, int amt) {
int n = coins.length;
int MAX = amt + 1;
// Initialize the dp table
List<int> dp = List.filled(amt + 1, MAX);
dp[0] = 0;
// State transitions
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the current amount a, do not choose coin i
dp[a] = dp[a];
} else {
// Take the smaller result of not choosing and choosing coin i
dp[a] = min(dp[a], dp[a - coins[i - 1]] + 1);
}
}
}
return dp[amt] != MAX ? dp[amt] : -1;
}
/* Coin change: space-optimized dynamic programming */
fn coin_change_dp_comp(coins: &[i32], amt: usize) -> i32 {
let n = coins.len();
let max = amt + 1;
// Initialize the dp table
let mut dp = vec![0; amt + 1];
dp.fill(max);
dp[0] = 0;
// State transitions
for i in 1..=n {
for a in 1..=amt {
if coins[i - 1] > a as i32 {
// If the coin exceeds the target amount, do not choose coin i
dp[a] = dp[a];
} else {
// Take the smaller result of not choosing and choosing coin i
dp[a] = std::cmp::min(dp[a], dp[a - coins[i - 1] as usize] + 1);
}
}
}
if dp[amt] != max {
return dp[amt] as i32;
} else {
-1
}
}
/* Coin change: space-optimized dynamic programming */
int coinChangeDPComp(int coins[], int amt, int coinsSize) {
int n = coinsSize;
int MAX = amt + 1;
// Initialize the dp table
int *dp = malloc((amt + 1) * sizeof(int));
for (int j = 1; j <= amt; j++) {
dp[j] = MAX;
}
dp[0] = 0;
// State transitions
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[a] = dp[a];
} else {
// Take the smaller result of not choosing and choosing coin i
dp[a] = myMin(dp[a], dp[a - coins[i - 1]] + 1);
}
}
}
int res = dp[amt] != MAX ? dp[amt] : -1;
// Free memory
free(dp);
return res;
}
/* Coin change: space-optimized dynamic programming */
fun coinChangeDPComp(coins: IntArray, amt: Int): Int {
val n = coins.size
val MAX = amt + 1
// Initialize the dp table
val dp = IntArray(amt + 1)
dp.fill(MAX)
dp[0] = 0
// State transitions
for (i in 1..n) {
for (a in 1..amt) {
if (coins[i - 1] > a) {
// If the coin value exceeds the current amount a, do not choose coin i
dp[a] = dp[a]
} else {
// Take the smaller result of not choosing and choosing coin i
dp[a] = min(dp[a], dp[a - coins[i - 1]] + 1)
}
}
}
return if (dp[amt] != MAX) dp[amt] else -1
}
### Coin change: space-optimized dynamic programming ###
def coin_change_dp_comp(coins, amt)
n = coins.length
_MAX = amt + 1
# Initialize the dp table
dp = Array.new(amt + 1, _MAX)
dp[0] = 0
# State transitions
for i in 1...(n + 1)
# Traverse in increasing order
for a in 1...(amt + 1)
if coins[i - 1] > a
# If the coin exceeds the current amount a, do not choose coin i
dp[a] = dp[a]
else
# Take the smaller result of not choosing and choosing coin i
dp[a] = [dp[a], dp[a - coins[i - 1]] + 1].min
end
end
end
dp[amt] != _MAX ? dp[amt] : -1
end
Visualize execution
14.5.3 Coin change problem II¶
Question
Given \(n\) coin denominations, where denomination \(i\) has value \(coins[i - 1]\), and a target amount \(amt\), each denomination may be used repeatedly. How many combinations of coins make the target amount? An example is shown in Figure 14-26.
Figure 14-26 Example input for coin change II
Description of Figure 14-26: Number of coin combinations in coin change II
Using unlimited coins of denominations 1, 2, and 5 to make target amount 5 yields 4 distinct combinations when order is ignored.
Coin change II likewise provides 3 unlimited denominations [1, 2, 5], but sets target amount amt = 5 and counts how many distinct coin combinations sum to 5 rather than minimizing coin count (arrangements with identical counts per denomination in different orders count as a single combination).
At the upper left, the coin table points via a thick gray rightward arrow to the pouch labeled "Target amount amt = 5". Below, the result box reads "Number of coin combinations: 4" and lists four coin-addition equations to the right of "Coin combinations:".
Below, the first table lists the input denominations and the second lists all four combinations in the order drawn, counting coins of each denomination from the equations (that count table is not drawn separately in the figure).
| ID i | Denomination |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 5 |
| Combination | Count of denomination 1 | Count of denomination 2 | Count of denomination 5 |
|---|---|---|---|
| 1+1+1+1+1 | 5 | 0 | 0 |
| 1+1+1+2 | 3 | 1 | 0 |
| 1+2+2 | 1 | 2 | 0 |
| 5 | 0 | 0 | 1 |
Case-by-case check from the input: if denomination 5 is used, only 1 coin of value 5 fits; if denomination 5 is not used, denomination 2 may be used 2, 1, or 0 times, completed by 1, 3, or 5 coins of denomination 1, respectively. That accounts for all four unordered combinations in the table with none missed.
1. Dynamic programming approach¶
This time, we count combinations, so the subproblem becomes the number of combinations that make amount \(a\) using the first \(i\) denominations. The \(dp\) table remains a two-dimensional matrix of size \((n+1) \times (amt + 1)\).
The number of combinations for the current state is the sum of those that exclude the current coin and those that include it. The state transition equation is:
A target of \(0\) can be made by choosing no coins, so initialize every first-column entry \(dp[i, 0]\) to \(1\). With no coins, any target \(>0\) is impossible, so the first-row entries \(dp[0, a]\) are \(0\).
2. Code implementation¶
def coin_change_ii_dp(coins: list[int], amt: int) -> int:
"""Coin change II: dynamic programming"""
n = len(coins)
# Initialize the dp table
dp = [[0] * (amt + 1) for _ in range(n + 1)]
# Initialize the first column
for i in range(n + 1):
dp[i][0] = 1
# State transitions
for i in range(1, n + 1):
for a in range(1, amt + 1):
if coins[i - 1] > a:
# If the coin value exceeds the current amount a, do not choose coin i
dp[i][a] = dp[i - 1][a]
else:
# Add the numbers of ways without and with coin i
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]]
return dp[n][amt]
/* Coin change II: dynamic programming */
int coinChangeIIDP(vector<int> &coins, int amt) {
int n = coins.size();
// Initialize the dp table
vector<vector<int>> dp(n + 1, vector<int>(amt + 1, 0));
// Initialize the first column
for (int i = 0; i <= n; i++) {
dp[i][0] = 1;
}
// State transitions
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[i][a] = dp[i - 1][a];
} else {
// Add the numbers of ways without and with coin i
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]];
}
}
}
return dp[n][amt];
}
/* Coin change II: dynamic programming */
int coinChangeIIDP(int[] coins, int amt) {
int n = coins.length;
// Initialize the dp table
int[][] dp = new int[n + 1][amt + 1];
// Initialize the first column
for (int i = 0; i <= n; i++) {
dp[i][0] = 1;
}
// State transitions
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[i][a] = dp[i - 1][a];
} else {
// Add the numbers of ways without and with coin i
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]];
}
}
}
return dp[n][amt];
}
/* Coin change II: dynamic programming */
int CoinChangeIIDP(int[] coins, int amt) {
int n = coins.Length;
// Initialize the dp table
int[,] dp = new int[n + 1, amt + 1];
// Initialize the first column
for (int i = 0; i <= n; i++) {
dp[i, 0] = 1;
}
// State transitions
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[i, a] = dp[i - 1, a];
} else {
// Add the numbers of ways without and with coin i
dp[i, a] = dp[i - 1, a] + dp[i, a - coins[i - 1]];
}
}
}
return dp[n, amt];
}
/* Coin change II: dynamic programming */
func coinChangeIIDP(coins []int, amt int) int {
n := len(coins)
// Initialize the dp table
dp := make([][]int, n+1)
for i := 0; i <= n; i++ {
dp[i] = make([]int, amt+1)
}
// Initialize the first column
for i := 0; i <= n; i++ {
dp[i][0] = 1
}
// State transitions: remaining rows and columns
for i := 1; i <= n; i++ {
for a := 1; a <= amt; a++ {
if coins[i-1] > a {
// If the coin exceeds the current target amount a, do not choose coin i
dp[i][a] = dp[i-1][a]
} else {
// Add the numbers of ways without and with coin i
dp[i][a] = dp[i-1][a] + dp[i][a-coins[i-1]]
}
}
}
return dp[n][amt]
}
/* Coin change II: dynamic programming */
func coinChangeIIDP(coins: [Int], amt: Int) -> Int {
let n = coins.count
// Initialize the dp table
var dp = Array(repeating: Array(repeating: 0, count: amt + 1), count: n + 1)
// Initialize the first column
for i in 0 ... n {
dp[i][0] = 1
}
// State transitions
for i in 1 ... n {
for a in 1 ... amt {
if coins[i - 1] > a {
// If the coin exceeds the current target amount a, do not choose coin i
dp[i][a] = dp[i - 1][a]
} else {
// Add the numbers of ways without and with coin i
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]]
}
}
}
return dp[n][amt]
}
/* Coin change II: dynamic programming */
function coinChangeIIDP(coins, amt) {
const n = coins.length;
// Initialize the dp table
const dp = Array.from({ length: n + 1 }, () =>
Array.from({ length: amt + 1 }, () => 0)
);
// Initialize the first column
for (let i = 0; i <= n; i++) {
dp[i][0] = 1;
}
// State transitions
for (let i = 1; i <= n; i++) {
for (let a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[i][a] = dp[i - 1][a];
} else {
// Add the numbers of ways without and with coin i
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]];
}
}
}
return dp[n][amt];
}
/* Coin change II: dynamic programming */
function coinChangeIIDP(coins: Array<number>, amt: number): number {
const n = coins.length;
// Initialize the dp table
const dp = Array.from({ length: n + 1 }, () =>
Array.from({ length: amt + 1 }, () => 0)
);
// Initialize the first column
for (let i = 0; i <= n; i++) {
dp[i][0] = 1;
}
// State transitions
for (let i = 1; i <= n; i++) {
for (let a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[i][a] = dp[i - 1][a];
} else {
// Add the numbers of ways without and with coin i
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]];
}
}
}
return dp[n][amt];
}
/* Coin change II: dynamic programming */
int coinChangeIIDP(List<int> coins, int amt) {
int n = coins.length;
// Initialize the dp table
List<List<int>> dp = List.generate(n + 1, (index) => List.filled(amt + 1, 0));
// Initialize the first column
for (int i = 0; i <= n; i++) {
dp[i][0] = 1;
}
// State transitions
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the current amount a, do not choose coin i
dp[i][a] = dp[i - 1][a];
} else {
// Add the numbers of ways without and with coin i
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]];
}
}
}
return dp[n][amt];
}
/* Coin change II: dynamic programming */
fn coin_change_ii_dp(coins: &[i32], amt: usize) -> i32 {
let n = coins.len();
// Initialize the dp table
let mut dp = vec![vec![0; amt + 1]; n + 1];
// Initialize the first column
for i in 0..=n {
dp[i][0] = 1;
}
// State transitions
for i in 1..=n {
for a in 1..=amt {
if coins[i - 1] > a as i32 {
// If the coin exceeds the target amount, do not choose coin i
dp[i][a] = dp[i - 1][a];
} else {
// Add the numbers of ways without and with coin i
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1] as usize];
}
}
}
dp[n][amt]
}
/* Coin change II: dynamic programming */
int coinChangeIIDP(int coins[], int amt, int coinsSize) {
int n = coinsSize;
// Initialize the dp table
int **dp = malloc((n + 1) * sizeof(int *));
for (int i = 0; i <= n; i++) {
dp[i] = calloc(amt + 1, sizeof(int));
}
// Initialize the first column
for (int i = 0; i <= n; i++) {
dp[i][0] = 1;
}
// State transitions
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[i][a] = dp[i - 1][a];
} else {
// Add the numbers of ways without and with coin i
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]];
}
}
}
int res = dp[n][amt];
// Free memory
for (int i = 0; i <= n; i++) {
free(dp[i]);
}
free(dp);
return res;
}
/* Coin change II: dynamic programming */
fun coinChangeIIDP(coins: IntArray, amt: Int): Int {
val n = coins.size
// Initialize the dp table
val dp = Array(n + 1) { IntArray(amt + 1) }
// Initialize the first column
for (i in 0..n) {
dp[i][0] = 1
}
// State transitions
for (i in 1..n) {
for (a in 1..amt) {
if (coins[i - 1] > a) {
// If the coin value exceeds the current amount a, do not choose coin i
dp[i][a] = dp[i - 1][a]
} else {
// Add the numbers of ways without and with coin i
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]]
}
}
}
return dp[n][amt]
}
### Coin change II: dynamic programming ###
def coin_change_ii_dp(coins, amt)
n = coins.length
# Initialize the dp table
dp = Array.new(n + 1) { Array.new(amt + 1, 0) }
# Initialize the first column
(0...(n + 1)).each { |i| dp[i][0] = 1 }
# State transitions
for i in 1...(n + 1)
for a in 1...(amt + 1)
if coins[i - 1] > a
# If the coin exceeds the current amount a, do not choose coin i
dp[i][a] = dp[i - 1][a]
else
# Add the numbers of ways without and with coin i
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]]
end
end
end
dp[n][amt]
end
Visualize execution
3. Space optimization¶
The space optimization is the same: remove the coin dimension:
def coin_change_ii_dp_comp(coins: list[int], amt: int) -> int:
"""Coin change II: space-optimized dynamic programming"""
n = len(coins)
# Initialize the dp table
dp = [0] * (amt + 1)
dp[0] = 1
# State transitions
for i in range(1, n + 1):
# Traverse in increasing order
for a in range(1, amt + 1):
if coins[i - 1] > a:
# If the coin value exceeds the current amount a, do not choose coin i
dp[a] = dp[a]
else:
# Add the numbers of ways without and with coin i
dp[a] = dp[a] + dp[a - coins[i - 1]]
return dp[amt]
/* Coin change II: space-optimized dynamic programming */
int coinChangeIIDPComp(vector<int> &coins, int amt) {
int n = coins.size();
// Initialize the dp table
vector<int> dp(amt + 1, 0);
dp[0] = 1;
// State transitions
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[a] = dp[a];
} else {
// Add the numbers of ways without and with coin i
dp[a] = dp[a] + dp[a - coins[i - 1]];
}
}
}
return dp[amt];
}
/* Coin change II: space-optimized dynamic programming */
int coinChangeIIDPComp(int[] coins, int amt) {
int n = coins.length;
// Initialize the dp table
int[] dp = new int[amt + 1];
dp[0] = 1;
// State transitions
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[a] = dp[a];
} else {
// Add the numbers of ways without and with coin i
dp[a] = dp[a] + dp[a - coins[i - 1]];
}
}
}
return dp[amt];
}
/* Coin change II: space-optimized dynamic programming */
int CoinChangeIIDPComp(int[] coins, int amt) {
int n = coins.Length;
// Initialize the dp table
int[] dp = new int[amt + 1];
dp[0] = 1;
// State transitions
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[a] = dp[a];
} else {
// Add the numbers of ways without and with coin i
dp[a] = dp[a] + dp[a - coins[i - 1]];
}
}
}
return dp[amt];
}
/* Coin change II: space-optimized dynamic programming */
func coinChangeIIDPComp(coins []int, amt int) int {
n := len(coins)
// Initialize the dp table
dp := make([]int, amt+1)
dp[0] = 1
// State transitions
for i := 1; i <= n; i++ {
// Traverse in increasing order
for a := 1; a <= amt; a++ {
if coins[i-1] > a {
// If the coin exceeds the current target amount a, do not choose coin i
dp[a] = dp[a]
} else {
// Add the numbers of ways without and with coin i
dp[a] = dp[a] + dp[a-coins[i-1]]
}
}
}
return dp[amt]
}
/* Coin change II: space-optimized dynamic programming */
func coinChangeIIDPComp(coins: [Int], amt: Int) -> Int {
let n = coins.count
// Initialize the dp table
var dp = Array(repeating: 0, count: amt + 1)
dp[0] = 1
// State transitions
for i in 1 ... n {
for a in 1 ... amt {
if coins[i - 1] > a {
// If the coin exceeds the current target amount a, do not choose coin i
dp[a] = dp[a]
} else {
// Add the numbers of ways without and with coin i
dp[a] = dp[a] + dp[a - coins[i - 1]]
}
}
}
return dp[amt]
}
/* Coin change II: space-optimized dynamic programming */
function coinChangeIIDPComp(coins, amt) {
const n = coins.length;
// Initialize the dp table
const dp = Array.from({ length: amt + 1 }, () => 0);
dp[0] = 1;
// State transitions
for (let i = 1; i <= n; i++) {
for (let a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[a] = dp[a];
} else {
// Add the numbers of ways without and with coin i
dp[a] = dp[a] + dp[a - coins[i - 1]];
}
}
}
return dp[amt];
}
/* Coin change II: space-optimized dynamic programming */
function coinChangeIIDPComp(coins: Array<number>, amt: number): number {
const n = coins.length;
// Initialize the dp table
const dp = Array.from({ length: amt + 1 }, () => 0);
dp[0] = 1;
// State transitions
for (let i = 1; i <= n; i++) {
for (let a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[a] = dp[a];
} else {
// Add the numbers of ways without and with coin i
dp[a] = dp[a] + dp[a - coins[i - 1]];
}
}
}
return dp[amt];
}
/* Coin change II: space-optimized dynamic programming */
int coinChangeIIDPComp(List<int> coins, int amt) {
int n = coins.length;
// Initialize the dp table
List<int> dp = List.filled(amt + 1, 0);
dp[0] = 1;
// State transitions
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the current amount a, do not choose coin i
dp[a] = dp[a];
} else {
// Add the numbers of ways without and with coin i
dp[a] = dp[a] + dp[a - coins[i - 1]];
}
}
}
return dp[amt];
}
/* Coin change II: space-optimized dynamic programming */
fn coin_change_ii_dp_comp(coins: &[i32], amt: usize) -> i32 {
let n = coins.len();
// Initialize the dp table
let mut dp = vec![0; amt + 1];
dp[0] = 1;
// State transitions
for i in 1..=n {
for a in 1..=amt {
if coins[i - 1] > a as i32 {
// If the coin exceeds the target amount, do not choose coin i
dp[a] = dp[a];
} else {
// Add the numbers of ways without and with coin i
dp[a] = dp[a] + dp[a - coins[i - 1] as usize];
}
}
}
dp[amt]
}
/* Coin change II: space-optimized dynamic programming */
int coinChangeIIDPComp(int coins[], int amt, int coinsSize) {
int n = coinsSize;
// Initialize the dp table
int *dp = calloc(amt + 1, sizeof(int));
dp[0] = 1;
// State transitions
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// If the coin exceeds the target amount, do not choose coin i
dp[a] = dp[a];
} else {
// Add the numbers of ways without and with coin i
dp[a] = dp[a] + dp[a - coins[i - 1]];
}
}
}
int res = dp[amt];
// Free memory
free(dp);
return res;
}
/* Coin change II: space-optimized dynamic programming */
fun coinChangeIIDPComp(coins: IntArray, amt: Int): Int {
val n = coins.size
// Initialize the dp table
val dp = IntArray(amt + 1)
dp[0] = 1
// State transitions
for (i in 1..n) {
for (a in 1..amt) {
if (coins[i - 1] > a) {
// If the coin value exceeds the current amount a, do not choose coin i
dp[a] = dp[a]
} else {
// Add the numbers of ways without and with coin i
dp[a] = dp[a] + dp[a - coins[i - 1]]
}
}
}
return dp[amt]
}
### Coin change II: space-optimized dynamic programming ###
def coin_change_ii_dp_comp(coins, amt)
n = coins.length
# Initialize the dp table
dp = Array.new(amt + 1, 0)
dp[0] = 1
# State transitions
for i in 1...(n + 1)
# Traverse in increasing order
for a in 1...(amt + 1)
if coins[i - 1] > a
# If the coin exceeds the current amount a, do not choose coin i
dp[a] = dp[a]
else
# Add the numbers of ways without and with coin i
dp[a] = dp[a] + dp[a - coins[i - 1]]
end
end
end
dp[amt]
end