Code RoomCourse selection tree
HardPrep Room Coding #1291

Course selection tree

CodingDatabases & SQLAlgorithms & data structuresSenior–Staff~40 min

You have a rooted tree of n courses (node 0 is the root). To take a course you must also take its parent (dependency). Each course i has a value val[i]. You may take at most k courses total. Return the maximum total value of a chosen connected subtree-respecting set that includes the constraint that a chosen node implies its parent is chosen. Equivalently: pick at most k nodes forming a set closed under 'take parent', maximizing value sum. Constraints: 1 <= n <= 300, 0 <= k <= n; parent[i] given for i>=1 (parent[i] < i); values may be negative.

Implement
max_value_with_deps(parent: list[int], val: list[int], k: int) → int
Examples
in[[-1,0,0,1],[3,4,2,5],3]out12
What a strong answer looks like

State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.

0:00 of about 40 min
InputExpectedGot
[[-1,0,0,1],[3,4,2,5],3]12not run yetsample