Coin Change

Fewest coins summing to amount — bottom-up unbounded knapsack.

Medium
Time O(n * amount) Space O(amount)
LeetCode
3 min read
dp knapsack

Problem#

Given coin denominations and an amount, return the fewest coins summing to amount, or -1 if impossible.

Examples#

  • coins = [1,2,5], amount = 113 (5+5+1)
  • coins = [2], amount = 3-1

Constraints#

  • 1 <= coins.length <= 12, 0 <= amount <= 10^4.

Approach#

dp[a] = fewest coins for amount a. Initialize to amount + 1 (sentinel for impossible). dp[0] = 0. Transition: dp[a] = min(dp[a - c] + 1) for each coin c <= a.

Solution#

Coin Change
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
vector<int> dp(amount + 1, amount + 1);
dp[0] = 0;
for (int a = 1; a <= amount; ++a) {
for (int c : coins) {
if (c <= a) dp[a] = min(dp[a], dp[a - c] + 1);
}
}
return dp[amount] > amount ? -1 : dp[amount];
}
};

Editorial#

Unbounded knapsack DP. Iterating amounts outer / coins inner allows each coin to be used unlimited times naturally. The amount + 1 sentinel makes “still infeasible after the loop” a single comparison.

Complexity#

  • Time: O(n * amount).
  • Space: O(amount).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.