Code Room
CodingMediumcod-g258
Subject Tree dpLevel Mid–Senior~30 minCommon in Algorithms & data structures interviewsIndustries Software development

Question

You are given a tree with n nodes (0-indexed) as an edge list, and a value array val. Choose a subset of nodes with maximum total value such that no two chosen nodes are adjacent (an independent set). The tree is rooted at node 0. Return the maximum achievable sum. 1 <= n <= 2000, 0 <= val[i] <= 10^4, edges has n-1 entries.

Implement
tree_max_independent(n: int, edges: list[list[int]], val: list[int]) → int
Examples
in[3,[[0,1],[0,2]],[1,2,3]]out5
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.