Pack Exactly K Items with Maximum Total Value
Dynamic ProgrammingAuto-graded · 17 test casesLast 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
kitems (no more, no fewer). - The combined weight of the chosen items must be ≤ capacity.
- If it is impossible to choose exactly
kitems within the weight limit, return-1.
Constraints
1 ≤ n ≤ 200(number of items)0 ≤ k ≤ n0 ≤ capacity ≤ 20001 ≤ weight[i] ≤ 100for each item0 ≤ value[i] ≤ 1000for each itemweightsandvaluesare lists of lengthn
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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Problem Restatement
We need a 0/1 knapsack variant with two simultaneous constraints: total weight ≤ capacity AND item count = exactly k. The standard 1D knapsack only enforces the weight constraint, so we extend the DP table with a second dimension tracking how many items have been included.
DP Definition
Define:
dp[j][w]= maximum total value achievable by selecting exactlyjitems with combined weight exactlyw.
A state is impossible if no such selection exists; we represent that with a sentinel value of -1 (or conceptually −∞).
Base case: dp[0][0] = 0 — zero items, zero weight, zero value.
All other entries start as impossible (-1).
Transition
For each item i (weight w_i, value v_i):
for j from min(i+1, k) down to 1:
for w from capacity down to w_i:
if dp[j-1][w - w_i] is reachable:
dp[j][w] = max(dp[j][w], dp[j-1][w - w_i] + v_i)
The reverse iteration (both over j and w) ensures each item is considered at most once per DP update step — the standard 0/1 knapsack trick applied to both dimensions.
Answer
After processing all items:
answer = max(dp[k][w] for w in 0..capacity)
return answer if answer != -1 else -1
Why It Is Correct
- Every path through the DP corresponds to a unique subset of items (reverse iteration prevents reuse).
- Selecting exactly
jitems with total weightwis only reachable if a feasible predecessor statedp[j-1][w-w_i]existed. - We maximize value greedily across all reachable weight values at count
k.
Complexity
| Time | O(n · k · capacity) |
| Space | O(k · capacity) |
With n ≤ 200, k ≤ 200, capacity ≤ 2000: at most 200 × 200 × 2000 = 80,000,000 operations — feasible in Python for the given constraints.
Reference Solution
from typing import List
def pack_exactly_k(weights: List[int], values: List[int], capacity: int, k: int) -> int:
n = len(weights)
NEG_INF = -1
# dp[j][w] = max value using exactly j items with total weight exactly w
dp = [[NEG_INF] * (capacity + 1) for _ in range(k + 1)]
dp[0][0] = 0
for i in range(n):
w_i = weights[i]
v_i = values[i]
for j in range(min(i + 1, k), 0, -1):
for w in range(capacity, w_i - 1, -1):
if dp[j - 1][w - w_i] != NEG_INF:
candidate = dp[j - 1][w - w_i] + v_i
if candidate > dp[j][w]:
dp[j][w] = candidate
best = max(dp[k])
return best if best != NEG_INF else -1