MCPcopy Create free account
hub / github.com/austingebauer/go-leetcode / coinChange

Function coinChange

coin_change_322/solution.go:7–39  ·  view source on GitHub ↗

Version 3: Bottom-up approach using filled slice with one above amount, which is one above max in scenario with denomination 1 * amount.

(coins []int, amount int)

Source from the content-addressed store, hash-verified

5// Version 3: Bottom-up approach using filled slice with one above amount,
6// which is one above max in scenario with denomination 1 * amount.
7func coinChange(coins []int, amount int) int {
8 if amount == 0 {
9 return 0
10 }
11
12 // Fill the array with values larger than amount
13 // At most, denomination 1 coins would supply change for 'n' 'n' times
14 mins := make([]int, amount+1)
15 for i := range mins {
16 mins[i] = amount + 1
17 }
18
19 // It takes 0 coins to make up the amount of 0
20 mins[0] = 0
21
22 for a := 1; a <= amount; a++ {
23 for c := 0; c < len(coins); c++ {
24 // coin is larger than current amount
25 if coins[c] > a {
26 continue
27 }
28
29 // mins[a] is initially large enough to after being filled into slice above
30 mins[a] = int(math.Min(float64(mins[a]), float64(mins[a-coins[c]]+1)))
31 }
32 }
33
34 if mins[amount] > amount {
35 return -1
36 }
37
38 return mins[amount]
39}
40
41// Version 2: Bottom-up approach using MaxInt32 for min comparison
42func coinChangeBottomUp1(coins []int, amount int) int {

Callers 1

Test_coinChangeFunction · 0.85

Calls

no outgoing calls

Tested by 1

Test_coinChangeFunction · 0.68