Cookie Box Order

Mediumdynamic programmingAlso known as Coin Change (fewest coins)

A bakery sells cookies only in boxes of a few fixed sizes, say 1, 6 and 10, with plenty of each. A school orders exactly 12 cookies: no more, no fewer.

Every box needs a ribbon and a label, so the baker wants as few boxes as possible.

Your task

Write fewestBoxes(sizes, count). sizes lists the box sizes; you may use any size as many times as you like. Return the smallest number of boxes whose sizes add up to exactly count.

If no mix of boxes adds up to exactly count, return -1. An order of 0 cookies needs 0 boxes.

fewestBoxes(sizes: int[], count: int) → int

Examples

Example 1
Input
sizes = [1, 6, 10]
count = 12
Output
2
Why

Two boxes of 6 make 12. Taking the biggest box first gives 10 + 1 + 1, which is 3 boxes, so choosing the biggest box first is not always best.

Example 2
Input
sizes = [4, 9]
count = 14
Output
-1
Why

Without a 9-box, 14 would have to be a multiple of 4, and it is not. With one 9-box, 5 cookies are left, and boxes of 4 cannot make 5. Two 9-boxes are already more than 14. So 14 is impossible.

Constraints

  • 1 ≤ sizes.length ≤ 12
  • 1 ≤ sizes[i] ≤ 1,000, all sizes different
  • 0 ≤ count ≤ 10,000
Start with brute force

Recursively try every box as the next one until you hit the count or overshoot. With sizes 1, 2 and 5 and a count of 100 there are far more than a billion sequences, and remainders like "40 cookies left" are solved again and again.

The greedy shortcut, always the biggest box that fits, is fast but wrong for sizes like [1, 6, 10].

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code