322. Coin Change
Asked at 35Amazon63Bloomberg61Microsoft53Meta50Google48Apple35Grab66Datadog92Geico88Mastercard86Pinterest76PayPal74Walmart Labs71Intuit70TikTok70carwale66ServiceNow66Accolite64Deutsche Bank62HashedIn62Qualcomm58Agoda57Uber57Adobe55Infosys54Morgan Stanley54PhonePe53Oracle52Affirm52Goldman Sachs45IBM44DE Shaw38Airbnb38Salesforce35Yandex28
Problem
Return the fewest coins that add up to amount, using unlimited coins of each denomination in coins, or −1 if it can't be done.
Example: coins = [1,2,5], amount = 11 → 3 (5 + 5 + 1); coins = [2], amount = 3 → -1
Constraints: amount ≤ 10⁴.
dp[a] = fewest coins summing to a = 1 + min(dp[a − c]) over coins. (BFS over amounts also works.)
coins [1,2,5], amount 11
a 0 1 2 3 4 5 6 7 8 9 10 11
dp 0 1 1 2 2 1 2 2 3 3 2 3
Complexity: O(amount × coins).
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
INF = amount + 1
dp = [0] + [INF] * amount
for a in range(1, amount + 1):
for c in coins:
if c <= a:
dp[a] = min(dp[a], dp[a - c] + 1)
return -1 if dp[amount] == INF else dp[amount]
assert Solution().coinChange([1, 2, 5], 11) == 3
assert Solution().coinChange([2], 3) == -1
assert Solution().coinChange([1], 0) == 0
class Solution {
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
Arrays.fill(dp, amount + 1);
dp[0] = 0;
for (int a = 1; a <= amount; a++)
for (int c : coins) if (c <= a) dp[a] = Math.min(dp[a], dp[a - c] + 1);
return dp[amount] > amount ? -1 : dp[amount];
}
}
func coinChange(coins []int, amount int) int {
inf := amount + 1
dp := make([]int, amount+1) // dp[a] = fewest coins summing to a
for a := 1; a <= amount; a++ {
dp[a] = inf
for _, c := range coins {
if c <= a {
dp[a] = min(dp[a], dp[a-c]+1)
}
}
}
if dp[amount] == inf {
return -1
}
return dp[amount]
}