lc-go/solutions/3/q322/solution.go

32 lines
643 B
Go

// Package q322 implements a solution for https://leetcode.com/problems/coin-change/
package q322
// Note: The cache size only needs to be min(max(coins), amount).
func coinChange(coins []int, amount int) int {
if amount == 0 {
return 0
}
cache := make([]int, amount+1)
cache[0] = amount + 1
for p := 1; p < len(cache); p *= 2 {
copy(cache[p:], cache[:p]) // fill with MAX+1
}
cache[0] = 0
for i := 1; i < len(cache); i++ {
for _, c := range coins {
if (i - c) < 0 {
continue
}
cache[i] = min(cache[i], cache[i-c]+1)
}
}
if cache[amount] > amount {
return -1
}
return cache[amount]
}
var _ = coinChange