Fill a Backpack With Exactly K Item Types
Dynamic ProgrammingAuto-graded · 17 test casesLast updated
Tests whether a candidate can apply 0/1 knapsack DP to determine the maximum total value achievable by selecting items that collectively use exactly K distinct item types within a weight budget.
Fill a Backpack With Exactly K Item Types
You are packing a bag for a trip. You have n items, each with a weight, a value, and a type label. Your bag has a maximum weight capacity W. You want to maximise the total value you carry, but with one extra rule: you must pick items that together use exactly k distinct type labels — no more, no fewer.
Each item may be taken at most once (0/1 knapsack).
Given the list of items and the integers W and k, return the maximum total value achievable under these constraints, or -1 if no valid selection exists.
Input
items: a list of[weight, value, type_label]triples, whereweightandvalueare positive integers andtype_labelis a non-negative integer.W: a positive integer — the weight capacity of the bag.k: a non-negative integer — the exact number of distinct type labels required.
Constraints
0 ≤ len(items) ≤ 2001 ≤ weight ≤ 50for each item1 ≤ value ≤ 1000for each item0 ≤ type_label ≤ 501 ≤ W ≤ 5000 ≤ k ≤ 51- If
k == 0, the only valid selection is the empty set (total value0), which is valid if and only if the empty set satisfies all constraints; return0in that case. - Return
-1if no subset satisfies both the weight and distinct-type constraints simultaneously.
Examples
Example 1
Input: max_value_exact_types([[2, 10, 0], [3, 14, 1], [1, 5, 1], [4, 8, 2]], 6, 2)
Output: 29
Example 2
Input: max_value_exact_types([[1, 100, 0], [1, 200, 0], [1, 50, 1]], 2, 1)
Output: 300
Example 3
Input: max_value_exact_types([[5, 10, 0], [5, 20, 1]], 4, 1)
Output: -1
Hints
Hint 1
Augment your DP state with a third dimension: the number of distinct types used so far. A state (item_index, remaining_weight, distinct_types_used) fully captures what you need.
Hint 2
When you add an item whose type is already present in your current selection, the distinct-type count does not increase — but tracking exactly which types are present is expensive. Instead, consider processing items grouped by type so you can cheaply track whether a type contributes at least one item.
Hint 3
After grouping items by type, run an outer loop over type groups and a standard 0/1 knapsack within each group. Maintain two DP tables: one for selections that have used exactly `t` types so far, and one for exactly `t+1`, updating them as you process each type group.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
This is a 0/1 knapsack with an extra "exactly k distinct types" constraint. The natural state is (types_used, weight_used) -> max_value. However, tracking which types are used would be exponential. Instead, we observe that what matters is only how many distinct types have contributed at least one item — not which specific types.
We therefore group items by type label and process one group at a time. For each group we decide:
- Skip the entire group (distinct-type count unchanged), or
- Take at least one item from the group (distinct-type count increases by exactly 1).
This neatly separates the "use this type" decision from the "which items within the type" decision.
DP Definition
dp[t][w] = maximum value achievable using exactly t distinct types and total weight exactly w, considering only the type groups processed so far. Unreachable states hold -1.
Initialisation: dp[0][0] = 0, all others -1.
Transition
For each type group g:
-
Mini 0/1 knapsack within
g: Computesome[dw]= best value obtainable by taking at least one item fromgwith total extra weightdw. This is a standard 0/1 knapsack over the group's items, maintaining two arrays (nonefor zero items taken,somefor one or more). -
Merge into main DP: For every reachable state
(t, w), combine with everysome[dw]to producenew_dp[t+1][w+dw]. States where the group is skipped are already carried forward by initialisingnew_dpas a copy ofdp.
Correctness
- Because items within a group are processed with a standard 0/1 knapsack, no item is counted twice.
- Because the outer loop walks one type group at a time and the
tdimension tracks exactly how many groups have contributed, the "exactlykdistinct types" constraint is satisfied precisely. - The
k == 0edge case returns0immediately (empty set). - If no selection fills exactly
ktypes within weightW,dp[k][*]remains all-1and we return-1.
Complexity
Let n = len(items), T = number of distinct type labels, W = weight capacity.
- Time: O(T · n/T · W · k) ≈ O(n · W · k). With n ≤ 200, W ≤ 500, k ≤ 51 this is at most ~5 million operations — very fast.
- Space: O(k · W) for the DP table, plus O(W) for the mini knapsack buffers.
Reference Solution
from typing import List
from collections import defaultdict
def max_value_exact_types(items: list, W: int, k: int) -> int:
if k == 0:
return 0
groups = defaultdict(list)
for weight, value, ttype in items:
groups[ttype].append((weight, value))
group_list = list(groups.values())
num_types = len(group_list)
if k > num_types:
return -1
NEG = -1
dp = [[NEG] * (W + 1) for _ in range(k + 1)]
dp[0][0] = 0
for group in group_list:
new_dp = [row[:] for row in dp]
none = [NEG] * (W + 1)
none[0] = 0
some = [NEG] * (W + 1)
for (w_item, v_item) in group:
new_none = none[:]
new_some = some[:]
for dw in range(W, -1, -1):
if dw + w_item > W:
continue
if none[dw] != NEG:
cand = none[dw] + v_item
if cand > new_some[dw + w_item]:
new_some[dw + w_item] = cand
if some[dw] != NEG:
cand = some[dw] + v_item
if cand > new_some[dw + w_item]:
new_some[dw + w_item] = cand
none = new_none
some = new_some
for t in range(k - 1, -1, -1):
for w in range(W + 1):
if dp[t][w] == NEG:
continue
for dw in range(1, W - w + 1):
if some[dw] == NEG:
continue
cand = dp[t][w] + some[dw]
if cand > new_dp[t + 1][w + dw]:
new_dp[t + 1][w + dw] = cand
dp = new_dp
ans = max(dp[k])
return ans if ans != NEG else -1