cconnected.
Understand the pattern. Find your own way.Find your starting point
Your learning feed/Idea 114 of 218
Ideas this builds on
1D dynamic programming114 / 218

Same coins, different question, different recurrence

Picture

“Coin change” names a setting, not an algorithm. You might want the fewest coins, the number of ordered sequences, or the number of unordered combinations. Before remembering a template, decide what counts as a different answer and whether coins can be reused.

Predict

With unlimited coins [1, 2] and target 3, are 1+2 and 2+1 one answer or two?

Reveal the reasoning

That depends on the output contract. Ordered sequences treat them as two; unordered combinations treat them as one. The mathematics cannot decide what the problem intended without that definition.

Go deeper: base values and loop order encode meaning

For minimum coins, define dp[a] as the fewest coins totaling exactly amount a. Assume distinct positive integer denominations and a nonnegative target. Zero amount needs zero coins; an unreachable amount starts at infinity.

def minimum_coins(coins, target):
    dp = [0] + [float("inf")] * target
    for amount in range(1, target + 1):
        for coin in coins:
            if coin <= amount:
                dp[amount] = min(dp[amount], 1 + dp[amount - coin])
    return -1 if dp[target] == float("inf") else dp[target]

assert minimum_coins([1, 3, 4], 6) == 2
assert minimum_coins([2], 3) == -1
assert minimum_coins([2], 0) == 0

To count, use dp[0]=1: there is one empty construction. With amount outside and coins inside, adding dp[amount-coin] counts ordered sequences by their final coin. With coins outside and increasing amounts inside, it counts unordered combinations by introducing coin types in a fixed order.

def combinations(coins, target):
    dp = [1] + [0] * target
    for coin in coins:
        for amount in range(coin, target + 1):
            dp[amount] += dp[amount - coin]
    return dp[target]

assert combinations([1, 2], 3) == 2  # 1+1+1, 1+2

Both examples use O(target × number_of_types) arithmetic operations and O(target) space. This is pseudo-polynomial in the numeric target, not polynomial in its binary encoding length. Duplicate denominations would overcount in the combination implementation; normalize or require distinct types as stated.

Analogy limit: unrestricted positive coins permit amount to shrink. A zero or negative denomination breaks that progress argument and can make some counting problems infinite.

Change one rule

Each coin is a physical item usable once. May an amount transition freely reuse the same coin again?

Check the variation

No. Track which items remain through an item index or a layer-aware table update. That is the availability issue in 0/1 knapsack.

Connect

Knapsack distinguishes reuse from single use. Greedy counterexamples explain why choosing the largest denomination need not minimize the coin count.