The Fewest Coins
Time limit1sMemory limit128 MB
Given coin denominations, bounded supplies that John holds, and unlimited shopkeeper change, find the minimum total number of coins exchanged so John pays at least T with exact change returned.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Greedy, Sorting, Brute force
- Solved
- No attempts yet
Problem
Farmer John has gone to town to buy some farm supplies. Being a very efficient man, he always pays for his goods so that the smallest number of coins changes hands; that is, the number of coins he uses to pay plus the number of coins he receives in change is minimized. Help him determine what this minimum number is.
Farmer John wants to buy cents of supplies (). The currency system has () different coins, with values (). Farmer John is carrying coins of value , coins of value , , and coins of value (). The shopkeeper has an unlimited supply of every coin and always makes change in the most efficient manner (using the fewest coins). Farmer John must, however, pay in a way that makes it possible to give exact change.
Input
- Line 1: Two space-separated integers, and .
- Line 2: space-separated integers, (the coin values).
- Line 3: space-separated integers, (how many of each coin Farmer John holds).
Output
- Line 1: A single integer, the minimum number of coins involved in the payment and the change. If it is impossible for Farmer John to pay and receive exact change, output .
Hint
When , Farmer John pays 75 cents using a 50-cent coin and a 25-cent coin, and receives a 5-cent coin in change, for a total of 3 coins used in the transaction.