KatInterview

Minimal Coin Exchange with Overpayment

Dynamic ProgrammingAuto-graded · 24 test cases
HardAuto-gradedDynamic Programmingdynamic-programmingarrays

Last updated

Find the minimum combined count of paid and received coins to settle a precise target value using dynamic programming.

You are purchasing an item of cost target using a set of available coin values given in coins.

When paying, you may overpay by tendering a total amount $P \ge \text{target}$. The vendor will then return change of amount $P - \text{target}$. Both the payment $P$ and the change $P - \text{target}$ must be represented using valid combinations of the coin values provided in coins.

Your goal is to find the minimum total count of coins exchanged during the transaction (the sum of coins you hand over plus the coins returned to you by the vendor).

If it is impossible to pay and receive change such that the net transaction equals target, return -1.

Assumptions & Rules

  • You may assume that the optimal overpayment does not require change exceeding target + max(coins).
  • Each coin denomination can be used an unlimited number of times for both paying and making change.

Constraints

  • 1 <= target <= 10,000
  • 1 <= len(coins) <= 20
  • 1 <= coins[i] <= 1,000

Examples

Example 1

Input: min_total_coins([1, 5, 10], 3)

Output: 3

Example 2

Input: min_total_coins([2, 5], 3)

Output: 2

Hints

Hint 1

Consider fixing the total payment amount P >= target. Once P is fixed, the payment (P) and change (P - target) become independent coin change problems.

Hint 2

You can compute a single DP array up to 2 * target + max(coins) that stores the minimum coins needed for any amount.

Hint 3

Iterate over all plausible payment amounts P from target to 2 * target + max(coins), and minimize dp[P] + dp[P - target].