PIXELBANKv9.1.0
Menu

Priority Context Packing Under a Token Budget

Problem Statement

Assemble the highest-value context that fits a token budget. Each candidate snippet has a token cost and a value; some are pinned (must always be included). Maximize total value without exceeding the budget.

Background

This is 0/1 knapsack with mandatory items. Pinned snippets are always included and their cost is subtracted from the budget first (if pinned items alone exceed the budget, they are still all included and the remaining budget is treated as 0 for the rest). The remaining optional snippets are chosen to maximize value within the leftover budget via exact 0/1 knapsack (integer costs). Return the max total value (pinned + chosen optional).

Your Task

def pack_context(snippets, budget):
  • snippets: list of {"cost": int, "value": int, "pinned": bool}.
  • Return the maximum achievable total value (int).

Input Format

  • snippets (list of dicts), budget (int).

Output Format

  • A single int (max total value).

Sample

s = [{"cost":5,"value":10,"pinned":True},{"cost":4,"value":40,"pinned":False},{"cost":3,"value":50,"pinned":False}]
print(pack_context(s, 10))

Output:

60

Example:

Input:
s = [{"cost":5,"value":10,"pinned":True},{"cost":4,"value":40,"pinned":False},{"cost":3,"value":50,"pinned":False}]
print(pack_context(s, 10))
Output:
60
Reasoning:
  • Isolate Pinned Items: The snippet with cost 5 and value 10 is pinned. Its cost is subtracted from the budget, leaving a remaining capacity of 10−5=510 - 5 = 5, and its value is set aside as a mandatory base of 1010.
  • Identify Optional Candidates: The remaining snippets are optional: one with cost 4 and value 40, and another with cost 3 and value 50.
  • Evaluate Combinations: With a remaining budget of 5, we check which optional items fit. The item with cost 4 fits (4≤54 \le 5), and the item with cost 3 fits (3≤53 \le 5). However, both cannot be selected together because their combined cost is 4+3=74 + 3 = 7, which exceeds the budget of 5.
  • Select Maximum Value: Comparing the individual values of the fitting items, the snippet with cost 3 has a value of 50, which is greater than the value of 40 for the snippet with cost 4. Thus, the optimal choice from the optional items yields a value of 50.
  • Calculate Total: The final total value is the sum of the pinned value and the best optional value: 10+50=6010 + 50 = 60.
  • The final output is 60

Constraints:

  • 0 <= budget <= 5000, costs/values are non-negative ints, len(snippets) <= 200.
  • All pinned items are always counted; remaining budget = max(budget - sum(pinned costs), 0).
  • Optional items chosen by exact 0/1 knapsack on the remaining budget.
solution.py

Test Results

0/0
Run code to see test results.