From 3b7f1e910e11ad2d59f2cffb80cf3f3c2495c265 Mon Sep 17 00:00:00 2001 From: Rastrian Date: Sun, 28 Feb 2021 09:08:27 -0300 Subject: [PATCH] Added Coin Change problem --- dynamic_programming/coin_change.rb | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 dynamic_programming/coin_change.rb diff --git a/dynamic_programming/coin_change.rb b/dynamic_programming/coin_change.rb new file mode 100644 index 0000000..08dbe65 --- /dev/null +++ b/dynamic_programming/coin_change.rb @@ -0,0 +1,30 @@ +def coinChangeMinimum(coins, amount) + dp = Array.new(amount+1,-1) + dp[0] = 0 + + coins.each do |coin| + (coin..amount).each do |i| + if dp[i-coin] != -1 + dp[i] = -1 == dp[i] ? dp[i-coin]+1 : [dp[i],dp[i-coin]+1].min + end + end + end + + dp[amount] + end + + def coinChangeCombinations(coins, amount) + dp = Array.new(coins.length+1) { Array.new(amount+1,0) } + dp[0][0] = 1 + (1..coins.length).each do |i| + (0..amount).each do |j| + dp[i][j] = dp[i-1][j] + (j < coins[i-1] ? 0 : dp[i][j-coins[i-1]]) + end + end + dp[coins.length][amount] + end + + coins = Array[2,4,5] + amount = 12 + puts "Number of combinations of getting change for " + amount.to_s + " is "+ coinChangeCombinations(coins, amount).to_s + "." + puts "Minimum number of coins required for " + amount.to_s + " is "+ coinChangeMinimum(coins, amount).to_s + "." \ No newline at end of file