KatInterview

Fewest Coins to Form Target Sum

Dynamic ProgrammingAuto-graded · 22 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingcoin-changeoptimization

Last updated

Tests dynamic programming with unbounded resources to compute the minimal coin count for a target value, handling impossible cases.

You have access to an unlimited supply of coins in various denominations and need to form a specific target sum.

Write a function that calculates the smallest number of coins required to reach exactly the target sum. When no valid combination exists, return -1. When the target is 0, return 0.

The denominations list may include repeated values and need not be in any particular order.

Function Signature

def fewest_coins(denominations: List[int], target: int) -> int:
    pass

Input

  • denominations: A list of positive integers representing available coin values
  • target: A non-negative integer sum to achieve

Output

An integer: the minimum coin count needed, or -1 if the target cannot be formed

Constraints

  • 1 <= len(denominations) <= 100
  • 1 <= denominations[i] <= 10^4
  • 0 <= target <= 10^4

Examples

Example 1

Input: fewest_coins([1, 2, 5], 11)

Output: 3

Example 2

Input: fewest_coins([2], 3)

Output: -1

Example 3

Input: fewest_coins([1, 2, 5], 0)

Output: 0

Hints

Hint 1

Consider building up from zero rather than breaking down from the target

Hint 2

A greedy approach of always taking the largest coin won't always give the optimal result

Hint 3

Think about this as a graph where each sum is a node and adding a coin creates an edge to a new sum