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
Scala DSA Implementation
basic.scala
object Main extends App {
def listString(values: Array[Int]): String = values.mkString("[", ", ", "]")
val coins = Array(1, 3, 4)
val target = 6
val inf = target + 1
val dp = Array.fill(target + 1)(inf)
dp(0) = 0
for (amount <- 1 to target) {
for (coin <- coins) {
if (amount >= coin) {
val candidate = dp(amount - coin) + 1
if (candidate < dp(amount)) dp(amount) = candidate
}
}
}
println(dp(target))
println(listString(dp))
}
Implementation notes
coinsis a ScalaArray[Int]with values1, 3, 4, andtargetis the fixedIntvalue6.val dp = Array.fill(target + 1)(inf)keeps the array reference fixed, while individual slots are still mutable.- The sentinel is
inf = target + 1, so the initial table is[0, 7, 7, 7, 7, 7, 7]afterdp(0) = 0. - The outer loop is amount-first:
for (amount <- 1 to target), thenfor (coin <- coins)checks each coin for that amount. if (amount >= coin)is the bounds guard before readingdp(amount - coin).- Each candidate is
dp(amount - coin) + 1; the slot changes only whencandidate < dp(amount). - The replay shows the table filling left to right:
[0, 1, 2, 1, 1, 2, 2], with amount6ending at2. println(dp(target))prints the answer first, thenlistString(dp)prints the full table withmkString("[", ", ", "]").
Output
2
[0, 1, 2, 1, 1, 2, 2]