KatInterview

Pack Expedition Gear Within Weight and Volume Limits

Dynamic ProgrammingAuto-graded · 16 test cases
MediumAuto-gradedDynamic Programmingdynamic programmingknapsackmemoization

Last updated

Tests the 2-constraint (weight + volume) knapsack variant using DP with memoization or tabulation to maximize the total utility of selected gear items.

Expedition Gear Packing

You are preparing for a wilderness expedition and must pack a selection of gear items into a single backpack. The backpack has two hard limits: a maximum weight capacity and a maximum volume capacity.

Each gear item has a weight (in grams), a volume (in cubic centimetres), and a utility score (a positive integer representing how useful it is on the trip). You may take at most one copy of each item (0/1 knapsack). Your goal is to choose a subset of items that fits within both limits while maximising the total utility score.

Task

Implement max_expedition_utility(weights, volumes, utilities, max_weight, max_volume).

  • weights[i], volumes[i], and utilities[i] describe the i-th item.
  • Return the maximum total utility achievable without exceeding either capacity.

Constraints

  • 1 ≤ len(weights) == len(volumes) == len(utilities) ≤ 100
  • 1 ≤ weights[i] ≤ 200
  • 1 ≤ volumes[i] ≤ 200
  • 1 ≤ utilities[i] ≤ 1000
  • 0 ≤ max_weight ≤ 2000
  • 0 ≤ max_volume ≤ 2000
  • If max_weight == 0 or max_volume == 0, no item can be packed; return 0.
  • If no item fits within both limits, return 0.

Examples

Example 1

Input: max_expedition_utility([3, 5, 2], [4, 3, 2], [10, 7, 5], 6, 6)

Output: 15

Example 2

Input: max_expedition_utility([10], [10], [42], 5, 10)

Output: 0

Example 3

Input: max_expedition_utility([1, 2, 3, 4], [1, 2, 3, 4], [1, 4, 9, 16], 5, 5)

Output: 17

Hints

Hint 1

Extend the classic 1-D knapsack DP table to two dimensions: dp[w][v] = best utility using at most w grams and v cubic centimetres.

Hint 2

Iterate over items one at a time and update the DP table in reverse order for both capacity dimensions to avoid using an item more than once.

Hint 3

The final answer is dp[max_weight][max_volume] after processing all items.