Change-making problem
The change-making problem addresses the question of finding the minimum number of coins that add up to a given amount of money. It is a special case of the integer knapsack problem, and has applications wider than just currency.
It is also the most common variation of the coin change problem, a general case of partition in which, given the available denominations of an infinite set of coins, the objective is to find out the number of possible ways of making a change for a specific amount of money, without considering the order of the coins.
It is weakly NP-hard, but may be solved optimally in pseudo-polynomial time by dynamic programming.
Mathematical definition
Coin values can be modeled by a set of distinct positive integer values, arranged in increasing order as through. The problem is: given an amount, also a positive integer, to find a set of non-negative integers, with each representing how often the coin with value is used, which minimize the total number of coinssubject to
Non-currency examples
An application of change-making problem can be found in computing the ways one can make a nine dart finish in a game of darts.Another application is computing the possible atomic composition of a given mass/charge peak in mass spectrometry.
Methods of solving
Simple dynamic programming
A classic dynamic programming strategy works upward by finding the combinations of all smaller values that would sum to the current threshold. Thus, at each threshold, all previous thresholds are potentially considered to work upward to the goal amount W. For this reason, this dynamic programming approach requires a number of steps that is O, where n'' is the number of types of coins.Implementation
The following is a dynamic programming implementation which uses a matrix to keep track of the optimal solutions to sub-problems, and returns the minimum number of coins, or "Infinity" if there is no way to make change with the coins given. A second matrix may be used to obtain the set of coins for the optimal solution.def _get_change_making_matrix:
m = 0 for _ in range] for _ in range]
for i in range:
m = float # By default there is no way of making change
return m
def change_making:
"""This function assumes that all coins are available infinitely.
if coins are only to be used once, change m to m.
n is the number to obtain with the fewest coins.
coins is a list or tuple with the available denominations.
"""
m = _get_change_making_matrix
for c, coin in enumerate:
for r in range:
# Just use the coin
if coin r:
m = 1
# coin cannot be included.
# Use the previous solution for making r,
# excluding coin
elif coin > r:
m = m
# coin can be used.
# Decide which one of the following solutions is the best:
# 1. Using the previous solution for making r.
# 2. Using the previous solution for making r - coin plus this 1 extra coin.
else:
m = min
return m