Fewest coins that cover every amount up to a limit
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Google, Microsoft and Meta. It tests greedy, math and sorting.
You are given a list of coin denominations (positive integers) and an integer max_amount. You may take any number of coins of each denomination.
Choose a multiset of coins so that every integer amount from 1 to max_amount can be paid exactly with some subset of the chosen coins. Each chosen coin can be used at most once per amount. Return the minimum number of coins you must choose. If no choice works, return -1.
def min_coins_to_cover(denominations: list[int], max_amount: int) -> int: ...
Constraints
-
0 <= len(denominations) <= 10^5,1 <= denominations[i] <= 10^18. Duplicates may appear. -
0 <= max_amount <= 10^18. Return0whenmax_amountis0. - Your solution must not take time proportional to
max_amount.
Example 1
- Input:
denominations = [1, 2, 5],max_amount = 10 - Output:
4 - Explanation: The coins
1, 2, 2, 5cover every amount from 1 to 10. For example, 4 = 2 + 2, 8 = 1 + 2 + 5 and 9 = 2 + 2 + 5. No set of 3 coins can do it.
Example 2
- Input:
denominations = [2, 5],max_amount = 10 - Output:
-1 - Explanation: The amount 1 can never be formed.
Clarifying questions
- Can we take as many coins of each denomination as we like? (Yes.)
- If there is no coin of value 1, is the answer always
-1formax_amount >= 1? - Can the reachable total overflow 64 bits? (Close to
2 * 10^18, so check.) - Should we return the coins themselves?
What a strong answer covers
- Tracks
reach, the largest amount such that every amount from 1 toreachcan be paid. It starts at 0. - Each step adds the largest denomination that is at most
reach + 1. That keeps every amount payable and growsreachthe most. If no denomination fits, the answer is-1. - Proves the greedy with an exchange argument: any coin above
reach + 1leaves a gap, and a smaller usable coin never growsreachmore. - Adds many copies of the same coin in one step with integer division, until the next denomination becomes usable or
max_amountis reached. So the time is O(m log m) and not proportional tomax_amount. - Tests both examples,
max_amount = 0,[1]with a huge limit, duplicates, and denominations far above the limit.
Follow-ups
- Each denomination has a limited supply.
- Return the chosen coins.
- Only a given set of amounts must be payable, not every amount up to the limit.
- Given a number of coins
c, find the largestmax_amountthey can cover.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.


