lc-go/solutions/3/q322/solution.go
2026-01-07 18:04:39 +09:00

31 lines
558 B
Go

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