|
| 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 | + ret := 0 |
| 33 | + for i := range denominations { |
| 34 | + c := denominations[len(denominations)-i-1] |
| 35 | + ret += amount / c |
| 36 | + amount = amount % c |
| 37 | + } |
| 38 | + if amount > 0 { |
| 39 | + return -1 |
| 40 | + } |
| 41 | + return ret |
| 42 | +} |
| 43 | + |
| 44 | +// CoinCombination returns a map with the specific combination of coins that gives |
| 45 | +// the minimum number. The keys are coin denominations and values are the number of |
| 46 | +// coins used for each denomination. |
| 47 | +// If the amount cannot be made with the given denominations, return an empty map. |
| 48 | +func CoinCombination(amount int, denominations []int) map[int]int { |
| 49 | + ret := make(map[int]int, 0) |
| 50 | + for i := range denominations { |
| 51 | + c := denominations[len(denominations)-i-1] |
| 52 | + ac := amount / c |
| 53 | + if ac == 0 { |
| 54 | + continue |
| 55 | + } |
| 56 | + if retc, ok := ret[c]; ok { |
| 57 | + ret[c] = retc + ac |
| 58 | + } else { |
| 59 | + ret[c] = ac |
| 60 | + } |
| 61 | + amount = amount % c |
| 62 | + } |
| 63 | + if amount > 0 { |
| 64 | + return map[int]int{} |
| 65 | + } |
| 66 | + return ret |
| 67 | +} |
0 commit comments