Complete the code to return the maximum path sum starting from the current node.
def max_gain(node): if not node: return 0 left_gain = max(max_gain(node.left), [1]) right_gain = max(max_gain(node.right), 0) return node.val + left_gain + right_gain
We use 0 as the minimum gain from a subtree to avoid decreasing the path sum.
Complete the code to update the global maximum path sum.
def max_gain(node): if not node: return 0 left_gain = max(max_gain(node.left), 0) right_gain = max(max_gain(node.right), 0) current_max_path = node.val + left_gain + right_gain max_gain.max_sum = max(max_gain.max_sum, [1]) return node.val + max(left_gain, right_gain)
We update the global max with the sum of the current node and both subtree gains.
Fix the error in the recursive call to avoid infinite recursion.
def max_gain(node): if not node: return 0 left_gain = max(max_gain([1]), 0) right_gain = max(max_gain(node.right), 0) current_max_path = node.val + left_gain + right_gain max_gain.max_sum = max(max_gain.max_sum, current_max_path) return node.val + max(left_gain, right_gain)
The recursive call must go to the left child, not the current node, to avoid infinite recursion.
Fill both blanks to complete the function that initializes and returns the maximum path sum.
def max_path_sum(root): max_gain.max_sum = [1] max_gain(root) return [2]
Initialize max_sum to negative infinity to handle negative values and return the updated max_sum.
Fill all three blanks to complete the dictionary comprehension that maps nodes to their maximum gains.
def max_gain_map(root): gain_map = {node: [1] for node in nodes if [2] return gain_map nodes = [root, root.left, root.right] max_gain_map_result = max_gain_map(root)
We map each non-null node to its max gain. The condition ensures nodes exist. The third blank is a distractor here and unused.
