DevPath

← All problems

Coin Change

Medium dynamic-programming

Description

Return the fewest coins needed to make amount using the given coin denominations, or -1 if it is impossible.

Constraints

1 <= coins <= 12; 0 <= amount <= 10000

Examples

Input: coins = [1,2,5], amount = 11

Output: 3

5 + 5 + 1

Hints (1)
  • Build a table of best counts up to amount.

Solutions

Bottom-up unbounded knapsack. · Time O(amount*coins) · Space O(amount)

func coinChange(coins []int, amount int) int {
    const inf = 1 << 30
    dp := make([]int, amount+1)
    for i := 1; i <= amount; i++ {
        dp[i] = inf
    }
    for a := 1; a <= amount; a++ {
        for _, c := range coins {
            if c <= a && dp[a-c]+1 < dp[a] {
                dp[a] = dp[a-c] + 1
            }
        }
    }
    if dp[amount] == inf {
        return -1
    }
    return dp[amount]
}

Create a free account to submit solutions, track progress and save problems.

Create account