Skip to content

Commit b153ab8

Browse files
Add solution for Challenge 22 (#700)
Co-authored-by: go-interview-practice-bot[bot] <230190823+go-interview-practice-bot[bot]@users.noreply.github.com>
1 parent 2b39f4a commit b153ab8

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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+
if amount == 0 {
33+
return 0
34+
}
35+
c := CoinCombination(amount, denominations)
36+
if len(c) == 0 {
37+
return -1
38+
}
39+
m := 0
40+
for _, val := range c {
41+
m += val
42+
}
43+
return m
44+
}
45+
46+
// CoinCombination returns a map with the specific combination of coins that gives
47+
// the minimum number. The keys are coin denominations and values are the number of
48+
// coins used for each denomination.
49+
// If the amount cannot be made with the given denominations, return an empty map.
50+
func CoinCombination(amount int, denominations []int) map[int]int {
51+
m := make(map[int]int)
52+
for i := len(denominations) - 1; amount > 0 && i >= 0; i-- {
53+
for amount > 0 && denominations[i] <= amount {
54+
amount -= denominations[i]
55+
m[denominations[i]]++
56+
}
57+
}
58+
if amount > 0 {
59+
return make(map[int]int)
60+
}
61+
return m
62+
}

0 commit comments

Comments
 (0)