1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
| package main
import (
"fmt"
"math"
)
func coinChange(coins []int, amount int) int {
// Initialize a slice to store
// the minimum number of coins needed for each amount.
minCoins := make([]int, amount+1)
for i := 1; i <= amount; i++ {
minCoins[i] = math.MaxInt32
}
// Iterate through each sub-amount from 1 to 'amount'.
for subAmount := 1; subAmount <= amount; subAmount++ {
// Consider each coin denomination.
for _, coin := range coins {
if coin <= subAmount {
// Update the minimum number of coins needed for the current sub-amount.
if minCoins[subAmount-coin]+1 < minCoins[subAmount] {
minCoins[subAmount] = minCoins[subAmount-coin] + 1
}
}
}
}
// If it's not possible to make up the amount, return -1.
# Otherwise, return the minimum count.
if minCoins[amount] == math.MaxInt32 {
return -1
}
return minCoins[amount]
}
func main() {
coins := []int{1, 2, 5}
amount := 11
result := coinChange(coins, amount)
fmt.Println(result) // Output: 3
}
|