Coin Change
Medium dynamic-programming
Description
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]
}
Bottom-up unbounded knapsack. · Time O(amount*coins) · Space O(amount)
function coinChange(coins, amount) {
const dp = new Array(amount + 1).fill(Infinity);
dp[0] = 0;
for (let a = 1; a <= amount; a++) {
for (const c of coins) if (c <= a && dp[a - c] + 1 < dp[a]) dp[a] = dp[a - c] + 1;
}
return dp[amount] === Infinity ? -1 : dp[amount];
}
Bottom-up unbounded knapsack. · Time O(amount*coins) · Space O(amount)
function coinChange($coins, $amount) {
$dp = array_fill(0, $amount + 1, PHP_INT_MAX);
$dp[0] = 0;
for ($a = 1; $a <= $amount; $a++) {
foreach ($coins as $c) {
if ($c <= $a && $dp[$a - $c] + 1 < $dp[$a]) { $dp[$a] = $dp[$a - $c] + 1; }
}
}
return $dp[$amount] === PHP_INT_MAX ? -1 : $dp[$amount];
}
Bottom-up unbounded knapsack. · Time O(amount*coins) · Space O(amount)
def coinChange(coins, amount):
inf = float("inf")
dp = [0] + [inf] * amount
for a in range(1, amount + 1):
for c in coins:
if c <= a and dp[a - c] + 1 < dp[a]:
dp[a] = dp[a - c] + 1
return -1 if dp[amount] == inf else dp[amount]
Bottom-up unbounded knapsack. · Time O(amount*coins) · Space O(amount)
function coinChange(coins: number[], amount: number): number {
const dp = new Array(amount + 1).fill(Infinity);
dp[0] = 0;
for (let a = 1; a <= amount; a++) {
for (const c of coins) if (c <= a && dp[a - c] + 1 < dp[a]) dp[a] = dp[a - c] + 1;
}
return dp[amount] === Infinity ? -1 : dp[amount];
}
Create a free account to submit solutions, track progress and save problems.
Create account