KatInterview

Maximize Museum Tour Value With Energy Budget

Dynamic ProgrammingAuto-graded · 17 test cases
MediumAuto-gradedDynamic Programmingdynamic programmingknapsackprerequisites

Last updated

Tests the 0/1 knapsack variant where you allocate a fixed energy budget across museum exhibits with costs and values, but some exhibits are only accessible after visiting a prerequisite.

Museum Tour Planning

You are planning a self-guided museum tour. The museum has n exhibits numbered 0 through n-1. Each exhibit has:

  • An energy cost costs[i] — how much energy it takes to visit exhibit i.
  • A satisfaction value values[i] — how much enjoyment you get from visiting it.
  • A prerequisite prereq[i] — you may only visit exhibit i if you have already decided to visit exhibit prereq[i] in your tour plan. If prereq[i] == -1, exhibit i has no prerequisite and can be visited freely.

You start with budget units of energy. You want to choose a subset of exhibits to visit (each at most once) that:

  1. Respects all prerequisite constraints (if you include exhibit i with prereq[i] != -1, you must also include exhibit prereq[i]).
  2. Has a total energy cost ≤ budget.
  3. Maximizes the total satisfaction value.

Return the maximum total satisfaction value achievable.

Prerequisite structure guarantee

The prerequisite graph is a forest (a collection of trees): each exhibit has at most one direct prerequisite, and there are no cycles. A prerequisite chain can be arbitrarily deep (e.g., exhibit 3 requires exhibit 1 which requires exhibit 0).

Constraints

  • 1 ≤ n ≤ 200
  • 1 ≤ len(costs) == len(values) == len(prereq) == n
  • 1 ≤ costs[i] ≤ 50
  • 1 ≤ values[i] ≤ 100
  • prereq[i] is -1 or a valid index j where j < i (prerequisites always have a smaller index, so the graph is a DAG)
  • 0 ≤ budget ≤ 10_000
  • If budget == 0, the answer is 0.
  • Multiple exhibits may share the same prerequisite (a node can have many children).

Examples

Example 1

Input: max_museum_satisfaction([3, 2, 5, 1], [10, 5, 15, 3], [-1, -1, 0, 0], 6)

Output: 18

Example 2

Input: max_museum_satisfaction([4, 3, 2, 6, 1], [8, 6, 4, 12, 2], [-1, 0, 0, 1, 1], 7)

Output: 14

Example 3

Input: max_museum_satisfaction([5, 5, 5], [10, 10, 10], [-1, 0, 1], 3)

Output: 0

Hints

Hint 1

Think of each tree in the forest as an independent subproblem. For a single tree rooted at node r, define dp[r][w] = max satisfaction from the subtree rooted at r using exactly w energy, where you MUST include r itself.

Hint 2

To combine a root node with its children subtrees, treat the children as independent knapsacks that you merge one by one into the root's DP table — this is the classic 'tree knapsack' or 'grouped knapsack on a tree' pattern.

Hint 3

After computing dp[r][w] for each root r in the forest, combine all roots with a final knapsack merge (roots have no mutual prerequisites, so they can be freely mixed).