"""Coin change: fewest coins and number of ways.

Idea
----
Fewest coins: ``best[a] = 1 + min(best[a - c] for each coin c)``, filled for
every amount from 1 up. Unlike the greedy "take the biggest coin" approach,
this is correct for every coin system (greedy fails for coins [1, 3, 4] and
amount 6: greedy gives 4+1+1, DP gives 3+3).

Number of ways: loop over coins in the *outer* loop so each combination is
counted once regardless of order.

Complexity
----------
Time:  O(amount * len(coins))
Space: O(amount)
"""

from collections.abc import Sequence


def min_coins(coins: Sequence[int], amount: int) -> int:
    """Return the fewest coins summing to ``amount``, or -1 if impossible."""
    INF = amount + 1
    best = [0] + [INF] * amount
    for a in range(1, amount + 1):
        for c in coins:
            if c <= a and best[a - c] + 1 < best[a]:
                best[a] = best[a - c] + 1
    return best[amount] if best[amount] != INF else -1


def count_ways(coins: Sequence[int], amount: int) -> int:
    """Return the number of coin combinations (order ignored) for ``amount``."""
    ways = [1] + [0] * amount
    for c in coins:
        for a in range(c, amount + 1):
            ways[a] += ways[a - c]
    return ways[amount]
