Dynamic programming · Medium
A payment simulator supports a configured set of positive token denominations. Tokens can be reused without limit. The simulator needs the smallest token count for a requested amount, including denomination sets where a greedy choice fails.
Return the fewest tokens whose values sum exactly to amount, or -1 when no combination reaches it.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
A JSON object { "coins": number[], "amount": number }.
Fields
- coins is an array of positive integer denominations. Duplicates are allowed.
- amount is a non-negative integer total.
Output
Return value
- Return an integer token count, not the chosen denominations.
- Amount 0 returns 0 even when coins is empty. A positive impossible amount returns -1.
- A denomination may be used more than once.
Constraints
- 0 <= coins.length <= 100; 1 <= coins[i] <= 100000.
- 0 <= amount <= 100000.
Examples
Example 1
{
"amount": 6,
"coins": [
1,
3,
4
]
}Returns
2Two 3s beat 4+1+1.
Example 2
{
"amount": 5,
"coins": [
4,
6
]
}Returns
-1No exact payment exists.
Required complexity
O(amount * max(1,c)) time and O(amount) extra space, where c is the number of denominations