← All questions
RareProgramming

How can you pack exactly n gifts at minimum cost when boxes of each size can be used any number of times?

Short answer
n = 8 → 13 (5 + 8)

Exercise

n = 8
box_sizes = [3, 4, 5]
box_costs = [5, 7, 8]

Solution

For each total, try every box that fits and add its cost to the optimum for the remaining gifts.

def min_cost(n, sizes, costs):
    dp = [0] + [float("inf")] * n
    for t in range(1, n + 1):
        for size, cost in zip(sizes, costs):
            if size <= t:
                dp[t] = min(dp[t], dp[t - size] + cost)
    return dp[n]

print(min_cost(8, [3, 4, 5], [5, 7, 8]))  # 13

The entry dp[t] is the least cost for exactly t gifts. Zero gifts cost nothing, and infinity marks a total still unreachable. Trying each possible last box allows any size to recur and never treats an unfilled remainder as a valid packing.

dp[0…8] = [0, ∞, ∞, 5, 7, 8, 10, 12, 13]. 8 = 3 + 5 = 4 + 4. min(5 + 8, 7 + 7) = 13.

Dynamic programming

Platforms

  • MAXIMUM

Download now and try it for free on your own tasks!

10 15 free credits • No credit card required
Version: Loading…

Choose the Windows app or the Chrome extension with phone controls.