#2925

Maximum Score After Applying Operations on a Tree

Medium
Dynamic ProgrammingTreeDepth-First SearchDynamic ProgrammingDepth-First SearchTree Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

In the optimal approach, we use dynamic programming with depth-first search (DFS) to calculate the maximum score for each subtree while keeping track of the sum of values. This allows us to efficiently determine which nodes to include in the score without violating the health condition of the tree.

⚙️

Algorithm

3 steps
  1. 1Step 1: Build the tree structure from the edges.
  2. 2Step 2: Use DFS to calculate the maximum score for each node while keeping track of the sum of values in the subtree.
  3. 3Step 3: For each node, decide whether to include its value based on the sum of its children's values.
solution.py23 lines
1# Full working Python code
2class Solution:
3    def maxScore(self, edges, values):
4        from collections import defaultdict
5        tree = defaultdict(list)
6        for a, b in edges:
7            tree[a].append(b)
8            tree[b].append(a)
9
10        def dfs(node, parent):
11            total = values[node]
12            score = 0
13            for child in tree[node]:
14                if child != parent:
15                    child_score, child_sum = dfs(child, node)
16                    score += child_score
17                    total += child_sum
18            if total > 0:
19                score += total
20            return score, total
21
22        max_score, _ = dfs(0, -1)
23        return max_score

Complexity note: This complexity is linear because we visit each node exactly once during the DFS traversal, making it efficient for trees.

  • 1Dynamic programming helps break down the problem into manageable subproblems.
  • 2Understanding tree traversal is crucial for efficiently solving tree-related problems.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.