Code Room
CodingHardcod-g726
Subject Tree dpLevel Senior–Staff~40 minCommon in Databases & SQL · Algorithms & data structures interviewsIndustries Software development

Question

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.

Vibe coding: describe the solution in plain language (or narrate it) and the coach grades your approach. Generating runnable code from your description is coming next.

Run or narrate your approach, then ask the coach.