Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created a code for the coin change problem in ruby #708

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions All Languages/Ruby Codes/coin_change_problem.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
def coin_change(coins, amount)
dp = Array.new(amount + 1, Float::INFINITY)
dp[0] = 0

coins.each do |coin|
(coin..amount).each do |i|
dp[i] = [dp[i], dp[i - coin] + 1].min
end
end

dp[amount] == Float::INFINITY ? -1 : dp[amount]
end

# Take user input for coin denominations
puts "Enter coin denominations separated by spaces:"
coins = gets.chomp.split.map(&:to_i)

# Take user input for the target amount
puts "Enter the target amount:"
amount = gets.chomp.to_i

result = coin_change(coins, amount)

if result == -1
puts "It's not possible to make change for the given amount with the provided coins."
else
puts "Minimum number of coins needed: #{result}"
end