Skip to content

Commit b397c7d

Browse files
authored
Implemented the Coin Change algorithm in R. (#170)
1 parent 39b9816 commit b397c7d

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

dynamic_programming/coin_change.r

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# Coin Change Problem
2+
#
3+
# The Coin Change problem finds the minimum number of coins needed to make a certain amount
4+
# using a given set of coin denominations.
5+
#
6+
# Time Complexity: O(amount * n) where n = number of coin denominations
7+
# Space Complexity: O(amount)
8+
#
9+
# Applications:
10+
# - Currency and cash management
11+
# - Making change in vending machines or payment systems
12+
# - Dynamic resource allocation
13+
# - Minimum cost problems in algorithms
14+
15+
# Function to compute minimum coins required
16+
coin_change <- function(coins, amount) {
17+
#' Compute minimum number of coins needed to make the given amount
18+
#' @param coins: Numeric vector of coin denominations
19+
#' @param amount: Total amount to make
20+
#' @return: Minimum number of coins required, or -1 if not possible
21+
22+
# Initialize DP array
23+
dp <- rep(Inf, amount + 1)
24+
dp[0 + 1] <- 0 # zero coins needed for amount 0
25+
26+
for (i in 1:amount) {
27+
for (coin in coins) {
28+
if (coin <= i) {
29+
dp[i + 1] <- min(dp[i + 1], 1 + dp[i - coin + 1])
30+
}
31+
}
32+
}
33+
34+
if (dp[amount + 1] == Inf) {
35+
return(-1)
36+
} else {
37+
return(dp[amount + 1])
38+
}
39+
}
40+
41+
# Function to print the DP table (for educational purposes)
42+
print_coin_change_dp <- function(dp, amount) {
43+
cat("DP Table for Coin Change:\n")
44+
for (i in 0:amount) {
45+
cat(sprintf("Amount %2d: %s\n", i, dp[i + 1]))
46+
}
47+
cat("\n")
48+
}
49+
50+
51+
# Example Usage & Testing
52+
cat("=== Coin Change Problem ===\n\n")
53+
54+
# Test 1: Basic Example
55+
coins <- c(1, 2, 5)
56+
amount <- 11
57+
cat("Coins:", paste(coins, collapse = ", "), "\n")
58+
cat("Amount:", amount, "\n")
59+
min_coins <- coin_change(coins, amount)
60+
cat("Minimum Coins Needed:", min_coins, "\n\n")
61+
62+
# Test 2: No solution case
63+
coins <- c(2, 4)
64+
amount <- 7
65+
cat("Coins:", paste(coins, collapse = ", "), "\n")
66+
cat("Amount:", amount, "\n")
67+
min_coins <- coin_change(coins, amount)
68+
cat("Minimum Coins Needed:", min_coins, "\n\n")
69+
70+
# Test 3: Larger dataset
71+
coins <- c(1, 3, 4, 5)
72+
amount <- 7
73+
cat("Coins:", paste(coins, collapse = ", "), "\n")
74+
cat("Amount:", amount, "\n")
75+
min_coins <- coin_change(coins, amount)
76+
cat("Minimum Coins Needed:", min_coins, "\n\n")

0 commit comments

Comments
 (0)