KatInterview

Minimum Coins to Reach a Money Amount

Dynamic ProgrammingAuto-graded · 22 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingdecimal-precisioncoin-change

Last updated

Tests dynamic programming on a coin-change problem where decimal monetary values must be safely converted to integers before solving.

You are given a list of coin denominations as decimal numbers and a target amount as a decimal number. Each denomination can be used as many times as needed. Find the fewest number of coins whose total value equals the target exactly. If no combination of coins sums to the target, return -1.

All monetary values use at most two decimal places (e.g., 0.25, 1.50, 3.00). Because floating-point numbers cannot represent most decimal fractions exactly, you must convert all values to integers (cents) before performing any computation. Do not run dynamic programming directly on floats.

Constraints:

  • 1 <= len(denominations) <= 100
  • 0 < each denomination <= 10,000
  • 0 <= target <= 10,000
  • All values have at most two digits after the decimal point
  • Aim for O(target * number_of_denominations) time after scaling and O(target) space

Examples

Example 1

Input: min_coins_for_amount([0.25, 0.5, 1], 1.25)

Output: 2

Example 2

Input: min_coins_for_amount([0.1, 0.2, 0.5], 0.7)

Output: 2

Example 3

Input: min_coins_for_amount([0.3, 0.5], 0.7)

Output: -1

Hints

Hint 1

Convert each decimal to cents by multiplying by 100, but beware that int(1.15 * 100) gives 114 due to float representation — use Decimal(str(value)) to avoid this.

Hint 2

Build a dp array where dp[v] stores the minimum coins needed to make exactly v cents, with dp[0] = 0 as the base case.

Hint 3

Use a sentinel value larger than any possible answer (like amount + 1) to mark unreachable amounts, then return -1 if dp[amount] is still the sentinel.