Cookie Box Order

Mediumdynamic programmingAlso known as Coin Change (fewest coins)

A bakery never sells loose cookies. They only come in boxes of a few fixed sizes, say 1, 6 and 10, and the shop has plenty of each. A school orders exactly 12 cookies for a class party: no more, no fewer.

Every box needs a ribbon and a label, so the baker wants to fill the order with 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. Grabbing the biggest box first gives 10 + 1 + 1, which is 3 boxes. Biggest-first is not always best.

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

With no 9-box you would need 14 / 4, which is not whole. With one 9-box, 5 is left, which 4s cannot make. Two 9-boxes are already too many. 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 exact count or overshoot. The number of sequences explodes: with sizes 1, 2 and 5 and a count of 100 there are far more than a billion of them, and the same remainders like "40 cookies left" are solved again and again.

The greedy shortcut, always taking 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