KatInterview

Fill a Backpack With Exactly K Item Types

Dynamic ProgrammingAuto-graded · 17 test cases
EasyAuto-gradedDynamic Programmingdynamic programmingknapsackmemoization

Last 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, where weight and value are positive integers and type_label is 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) ≤ 200
  • 1 ≤ weight ≤ 50 for each item
  • 1 ≤ value ≤ 1000 for each item
  • 0 ≤ type_label ≤ 50
  • 1 ≤ W ≤ 500
  • 0 ≤ k ≤ 51
  • If k == 0, the only valid selection is the empty set (total value 0), which is valid if and only if the empty set satisfies all constraints; return 0 in that case.
  • Return -1 if 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.