← Questions

Fewest coins that cover every amount up to a limit

0

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. Return 0 when max_amount is 0.
  • 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, 5 cover 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 -1 for max_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 to reach can be paid. It starts at 0.
  • Each step adds the largest denomination that is at most reach + 1. That keeps every amount payable and grows reach the most. If no denomination fits, the answer is -1.
  • Proves the greedy with an exchange argument: any coin above reach + 1 leaves a gap, and a smaller usable coin never grows reach more.
  • Adds many copies of the same coin in one step with integer division, until the next denomination becomes usable or max_amount is reached. So the time is O(m log m) and not proportional to max_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 largest max_amount they can cover.

Where it's asked

What it tests

greedy · math · sorting

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding