Build a one-dimensional table where each amount stores the fewest coins needed to make it.

Algorithm

@steps

  1. Initialize dp[0] = 0 and all other amounts to an unreachable sentinel.
  2. Scan amounts from 1 through 6.
  3. For each coin, read the earlier cell dp[amount - coin] when it exists.
  4. Write the smallest candidate into the current amount.
  5. Print both the final answer and the full DP array. @end @complexity
  • Time: O(target * coin_count)
  • Space: O(target) @end
bottom-up dynamic programming `dp[a]` is solved from already-computed smaller amounts, so every table cell has a visible dependency.

Ruby DSA Implementation

basic.rb
def list_string(values)
  "[" + values.join(", ") + "]"
end

coins = [1, 3, 4]
target = 6
inf = target + 1
dp = Array.new(target + 1, inf)
dp[0] = 0
(1..target).each do |amount|
  coins.each do |coin|
    next if amount < coin
    candidate = dp[amount - coin] + 1
    dp[amount] = candidate if candidate < dp[amount]
  end
end
puts dp[target]
puts list_string(dp)

@end @output 2 [0, 1, 2, 1, 1, 2, 2] @end