Python coding

Ways to pay an amount

You have an unlimited supply of coins of each value in coins. Return how many different combinations of coins add up to exactly amount. A combination is defined by how many coins of each value it uses, not by their order: with [1, 2], paying 1 + 1 + 2 and 2 + 1 + 1 is the same combination. An amount of 0 has exactly one combination, the empty one.

coins holds 1 to 50 distinct positive integers and amount goes from 0 to 2,000. Aim for O(len(coins) · amount) time.

Besides the tests, one large input (an amount of 150) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • ways_to_pay([1,2], 4) → 3
  • ways_to_pay([5,2,3], 10) → 4
  • ways_to_pay([4,6], 7) → 0
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Count, don't list. But adding up ways[a - c] over every coin c counts 1 + 2 and 2 + 1 as two ways: that counts orders, not combinations.

Hint 2

Put the coins in the outer loop: once coin c is processed, ways[a] counts combinations of the coins seen so far, each in one order. Going upward through the amounts lets c repeat.

Solution and why it works
pythonO(len(coins) · amount) · O(amount)
def ways_to_pay(coins: list[int], amount: int) -> int:
    ways = [1] + [0] * amount            # ways[a]: combinations of the coins so far that sum to a
    for c in coins:                      # coins outside: each combination is built in one order only
        for a in range(c, amount + 1):   # upward, so coin c can be used again
            ways[a] += ways[a - c]
    return ways[amount]

With the coins in the outer loop, every combination is built in one fixed order (all coins of the first value, then the second…), so it is counted exactly once; going upward through the amounts lets each coin repeat. That's amount + 1 counters, updated once per coin. Swapping the two loops is the trap: it counts ordered sequences, 5 instead of 3 for [1, 2] and 4. Plain recursion walks the combinations one by one.

Related lab: Big-O growth