All problems
0039MediumArrayDynamic ProgrammingBreadth-First SearchKnapsack ProblemComplete Knapsack

Fewest Tokens for the Charge

Tracked in this browser only
Write code

Trains the technique from

LeetCode 322Coin Change

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A toll booth accepts plastic tokens. The integer array values lists the token types the booth recognises, where each entry is the credit one token of that type carries, and the booth's dispenser holds an unlimited number of tokens of every listed type.

A driver owes charge credits and the booth gives no change, so the tokens dropped in must add up to charge exactly. Return the smallest number of tokens that does it. If no combination of the listed types adds up to charge, return -1.

A charge of 0 credits is settled by dropping in nothing at all, so the answer there is 0.

Examples

Example 1

Input
values = [1, 4, 6], charge = 8
Output
2

Two 4-credit tokens settle the charge. Reaching for the 6 first would force two 1s after it, which costs three tokens.

Example 2

Input
values = [7, 5], charge = 3
Output
-1

Every token carries more credit than the charge, and the booth gives no change, so the charge cannot be settled.

Example 3

Input
values = [3, 10], charge = 0
Output
0

Nothing is owed, so no token is needed.

Constraints

  • 1 <= values.length <= 12
  • 1 <= values[i] <= 2^31 - 1
  • 0 <= charge <= 10^4
  • Every token type may be used any number of times

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def fewest_tokens(values: list[int], charge: int) -> int:
Java
public int fewestTokens(int[] values, int charge)
September 7
Apply