progress

~/problems / 2-D dynamic programming / Knapsack and coin change

Prize stall with limited stock

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~20 min

At the end of a school fair you have tokens to spend. Each kind of prize is (cost, joy, stock): a copy costs cost tokens, gives joy, and only stock copies exist. Take any number of each kind up to its stock, within tokens.

Implement max_joy(tokens: int, prizes: list[tuple[int, int, int]]) -> int: the largest total joy.

max_joy(12, [(4, 5, 2), (3, 4, 1), (6, 8, 1)])  # 14   two of the first (8 tokens) + the second (3 tokens)
                                                #      three of the first would give 15, but only 2 are in stock
max_joy(2, [(5, 100, 3)])                       # 0    can't afford anything

Up to 2000 tokens and 30 kinds of prize, stock <= 5. Taking nothing gives 0.

⭐ Bonus: a speed test with 30 kinds and 2000 tokens earns a star with a table over token amounts. Trying every combination of counts (up to 6^30) is hopeless.

Show hint

a kind with stock = 3 is three separate copies, each usable once, so this is 0/1 knapsack: best[t] = most joy within t tokens, looping t downwards for each copy.

Topic: Knapsack and coin change. 0/1 vs unbounded; loop order decides combinations vs permutations.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc