Recursion and Dynamic Programming
Coin Change (Bottom-Up)
Build a one-dimensional table where each amount stores the fewest coins needed to make it.
Algorithm
Steps
- Initialize
dp[0] = 0and all other amounts to an unreachable sentinel. - Scan amounts from
1through6. - For each coin, read the earlier cell
dp[amount - coin]when it exists. - Write the smallest candidate into the current amount.
- Print both the final answer and the full DP array.
Complexity
- Time: O(target * coin_count)
- Space: O(target)
bottom-up dynamic programming
`dp[a]` is solved from already-computed smaller amounts, so every table cell has a visible dependency.
Visual walkthrough
Kotlin DSA Implementation
basic.kt
fun listString(values: IntArray): String = values.joinToString(prefix = "[", postfix = "]")
fun main() {
val coins = intArrayOf(1, 3, 4)
val target = 6
val inf = target + 1
val dp = IntArray(target + 1) { inf }
dp[0] = 0
for (amount in 1..target) {
for (coin in coins) {
if (amount >= coin) {
val candidate = dp[amount - coin] + 1
if (candidate < dp[amount]) dp[amount] = candidate
}
}
}
println(dp[target])
println(listString(dp))
}
Output
2
[0, 1, 2, 1, 1, 2, 2]
Implementation notes
- Kotlin stores
coinsas a primitiveIntArrayfromintArrayOf(1, 3, 4);target,inf, and loop indexes are non-nullIntvalues. val dp = IntArray(target + 1) { inf }creates a mutable primitiveIntArrayof length7, filled with the sentineltarget + 1, which is7.- The
dpbinding is aval, but its cells mutate in place;dp[0] = 0creates the traced initial table[0, 7, 7, 7, 7, 7, 7]. - The outer loop is
for (amount in 1..target), and the inner loop scansfor (coin in coins), so each amount considers coins1,3, then4. if (amount >= coin)guardsdp[amount - coin]so indexes never go negative.- The update uses
val candidate = dp[amount - coin] + 1and writesdp[amount] = candidateonly whencandidate < dp[amount]; there is no separate unreachable-state check in this checked input. - The trace shows
dpprogressing through[0, 1, 7, 7, 7, 7, 7],[0, 1, 2, 7, 7, 7, 7],[0, 1, 2, 1, 1, 2, 7], and finally[0, 1, 2, 1, 1, 2, 2]. println(dp[target])prints2, andprintln(listString(dp))formats the fullIntArrayas[0, 1, 2, 1, 1, 2, 2].