KatInterview

Pack Exactly K Items with Maximum Total Value

Dynamic ProgrammingAuto-graded · 17 test cases
MediumAuto-gradedDynamic Programmingdynamic programmingknapsack2d dp

Last updated

Tests the candidate's ability to apply a 2D knapsack variant requiring exactly a fixed item count while maximizing value, combining count and capacity constraints via DP.

Pack Exactly K Items with Maximum Total Value

You are packing a bag for a trip. You have n items, each described by a weight and a value. Your bag has a maximum capacity (total weight it can hold), and you want to pick exactly k items to place in it.

Return the maximum total value achievable by choosing exactly k items whose combined weight does not exceed capacity. If no valid selection exists, return -1.

Details

  • Each item may be used at most once.
  • You must choose exactly k items (no more, no fewer).
  • The combined weight of the chosen items must be ≤ capacity.
  • If it is impossible to choose exactly k items within the weight limit, return -1.

Constraints

  • 1 ≤ n ≤ 200 (number of items)
  • 0 ≤ k ≤ n
  • 0 ≤ capacity ≤ 2000
  • 1 ≤ weight[i] ≤ 100 for each item
  • 0 ≤ value[i] ≤ 1000 for each item
  • weights and values are lists of length n

Examples

Example 1

Input: pack_exactly_k([2, 3, 4, 5], [3, 4, 5, 6], 8, 2)

Output: 10

Example 2

Input: pack_exactly_k([1, 2, 3], [10, 20, 30], 5, 3)

Output: -1

Example 3

Input: pack_exactly_k([5, 5, 5], [10, 20, 30], 8, 1)

Output: 30

Hints

Hint 1

Think of a 2D DP table where one dimension tracks the number of items chosen so far and the other tracks remaining (or used) weight capacity.

Hint 2

Define dp[j][w] as the maximum value when you have selected exactly j items using exactly w units of weight. Transition: for each new item, decide to include it or skip it.

Hint 3

Initialize dp[0][0] = 0 and all other states as -infinity (impossible). At the end, take the maximum over dp[k][w] for all w ≤ capacity, returning -1 if that maximum is still -infinity.