Skip to content

Commit 3a73fa5

Browse files
Add solution for Challenge 22
1 parent b33456d commit 3a73fa5

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
)
6+
7+
func main() {
8+
// Standard U.S. coin denominations in cents
9+
denominations := []int{1, 5, 10, 25, 50}
10+
11+
// Test amounts
12+
amounts := []int{87, 42, 99, 33, 7}
13+
14+
for _, amount := range amounts {
15+
// Find minimum number of coins
16+
minCoins := MinCoins(amount, denominations)
17+
18+
// Find coin combination
19+
coinCombo := CoinCombination(amount, denominations)
20+
21+
// Print results
22+
fmt.Printf("Amount: %d cents\n", amount)
23+
fmt.Printf("Minimum coins needed: %d\n", minCoins)
24+
fmt.Printf("Coin combination: %v\n", coinCombo)
25+
fmt.Println("---------------------------")
26+
}
27+
}
28+
29+
// MinCoins returns the minimum number of coins needed to make the given amount.
30+
// If the amount cannot be made with the given denominations, return -1.
31+
func MinCoins(amount int, denominations []int) int {
32+
// TODO: Implement this function
33+
max := amount + 1
34+
dp := make([]int, max)
35+
for i := 1; i < len(dp); i++ {
36+
dp[i] = max
37+
}
38+
39+
for i := 1; i <= amount; i++ {
40+
for _, coin := range denominations {
41+
if i >= coin {
42+
dp[i] = min(dp[i], dp[i-coin] + 1)
43+
}
44+
}
45+
}
46+
47+
if dp[amount] >= max {
48+
return -1
49+
}
50+
51+
return dp[amount]
52+
}
53+
54+
// CoinCombination returns a map with the specific combination of coins that gives
55+
// the minimum number. The keys are coin denominations and values are the number of
56+
// coins used for each denomination.
57+
// If the amount cannot be made with the given denominations, return an empty map.
58+
func CoinCombination(amount int, denominations []int) map[int]int {
59+
// TODO: Implement this function
60+
if amount == 0 || len(denominations) == 0 {
61+
return make(map[int]int)
62+
}
63+
64+
max := amount + 1
65+
dp := make([]int, max)
66+
combinations := make([]map[int]int, max)
67+
for i := 1; i < len(dp); i++ {
68+
dp[i] = max
69+
combinations[i] = make(map[int]int)
70+
}
71+
combinations[0] = make(map[int]int)
72+
73+
for i := 1; i <= amount; i++ {
74+
for _, coin := range denominations {
75+
if i >= coin && dp[i] > dp[i-coin] + 1 {
76+
dp[i] = dp[i-coin] + 1
77+
78+
combinations[i] = make(map[int]int)
79+
for k, v := range combinations[i-coin] {
80+
combinations[i][k] = v
81+
}
82+
combinations[i][coin]++
83+
}
84+
}
85+
}
86+
87+
if dp[amount] >= max {
88+
return make(map[int]int)
89+
}
90+
91+
return combinations[amount]
92+
}

0 commit comments

Comments
 (0)