A simple counter example would be two types of coins (weight,value) = {(2,3), (3,3)} , with a copy that weighs 4. You will try to put the βworstβ coin with a weight of 3 and will not be able to match the weight four. But the situation is very possible with 2 * (2,3) coins,
This can be solved very similar to the knapsack problem using some changes in Dynamic Programming :
The idea is to simulate an exhaustive search. At each step, you look at the current coin of the candidate, and you have two options: take or go to the next coin.
f(x,i) = INFINITY x < 0 //too much weight f(0,i) = 0 //valid stop clause, filled the piggy completely. f(x,0) = INFINITY x > 0 //did not fill the piggy f(x,i) = min{ f(x,i-1) , f(x-weight[i], i) + value[i] } //take minimal guaranteed value ^ ^ coin is not used use this coin anymore
Call with f(Weight,#coins_in_currency)
The time complexity of this solution when using DP (bottom to top or top to bottom) is O(n*W) , where W is the desired weight of the pig, and n is the number of coins in currency.
source share