-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
83 lines (69 loc) · 1.55 KB
/
main.go
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println("TOP DOWN")
fmt.Println(coinChangeTopDown([]int{1, 2, 5}, 3) == 2)
fmt.Println(coinChangeTopDown([]int{1, 2, 5}, 11) == 3)
fmt.Println(coinChangeTopDown([]int{2}, 3) == -1)
fmt.Println(coinChangeTopDown([]int{2}, 0) == 0)
fmt.Println("BOTTOM UP")
fmt.Println(coinChangeBottomUp([]int{1, 2, 5}, 3) == 2)
fmt.Println(coinChangeBottomUp([]int{1, 2, 5}, 11) == 3)
fmt.Println(coinChangeBottomUp([]int{2}, 3) == -1)
fmt.Println(coinChangeBottomUp([]int{2}, 0) == 0)
}
func coinChangeTopDown(coins []int, amount int) int {
if amount == 0 {
return 0
}
memo := make([]int, amount+1)
for i := range memo {
memo[i] = -1
}
var dp func(amount int) int
dp = func(amount int) int {
if amount == 0 {
return 0
}
if amount < 0 {
return math.MaxInt
}
if memo[amount] == -1 {
minCoins := math.MaxInt
for _, coin := range coins {
if coinsUsed := dp(amount - coin); coinsUsed != math.MaxInt {
minCoins = min(minCoins, coinsUsed+1)
}
}
memo[amount] = minCoins
}
return memo[amount]
}
coinsUsed := dp(amount)
if coinsUsed == math.MaxInt {
return -1
}
return coinsUsed
}
func coinChangeBottomUp(coins []int, amount int) int {
dp := make([]int, 0, amount+1)
for range amount + 1 {
dp = append(dp, math.MaxInt)
}
dp[0] = 0
for a := 1; a <= amount; a++ {
for _, c := range coins {
if a-c < 0 || dp[a-c] == math.MaxInt {
continue
}
dp[a] = min(dp[a], dp[a-c]+1)
}
}
if dp[len(dp)-1] == math.MaxInt {
return -1
}
return dp[len(dp)-1]
}