Making Change With at Most k Coins
Here is a variation on the change-making problem. Given an unlimited supply of coins of denominations x[1], x[2], …, x[n], we wish to make change for a value v using at most k coins. For instance, if the denominations are 5 and 10 and k = 6, then we can make change for 55 but not for 65. Give an efficient dynamic-programming algorithm.
A new constraint ("at most k") ⇒ add a dimension counting coins used. This is the standard move: a bound on a resource becomes a table axis.
Same take/skip structure as 6.17, but taking a coin of denomination i also spends one from the coin budget: c → c−1. Base case T(i,b,0)=false for b>0 enforces the "no coins left" wall.
Whenever a problem adds "at most / exactly k of something," add a k-sized axis and decrement it on the relevant branch. This is how most exam variants are built: take a canonical recurrence and bolt on one dimension. Recognizing that turns a "novel" problem into a solved one.
Instead of a Boolean 3-D table, store the minimum number of coins and compare to k only at the end. k never needs to be a dimension.
Extraction: answer is yes iff C(n, v) ≤ k. Subproblems O(nv), fill O(nv), extract O(1). This is strictly tighter (no factor of k) and uses ∞, a legal numeric primitive. Both this and the 3-D Boolean version above earn full credit; lead with this if efficiency is rewarded.
Optional pseudocode not required by Ed #9
A mechanical translation of the leaner 2-D min-coins form (version B).
function ChangeAtMostK(x[1..n], v, k): for i = 0 to n: C[i][0] = 0 for b = 1 to v: C[0][b] = ∞ for i = 1 to n: for b = 1 to v: if x[i] > b: C[i][b] = C[i-1][b] else: C[i][b] = min(C[i-1][b], 1 + C[i][b - x[i]]) return C[n][v] <= k # true = makeable with ≤ k coins
Try it yourself
worked example + self-testMin-coins form: C(b)=minc(1+C(b−c)). Answer yes iff C(v) ≤ k.
denominations x = [5, 10] v = 55 k = 6
denominations x = [1, 5, 10] v = 27 k = 5