Recursion and Trees
78 / 170Recursion and TreesLesson 11 of 13About 53 min
The same idea as the diameter lesson, with one extra decision that makes it much harder.
Write down what the node returns and what it updates, as two sentences. Decide whether a child's contribution can be declined, and clamp if so. Initialize the running best to something no real answer can beat. Check the all-negative case.
Those four steps solve this problem and every variant of it. The pattern is worth more than the problem.
The only node in the tree holds -3 and has no children, so the answer must be -3. This shows what the running best becomes under two different starting values. Type the two lines it prints.
def top_out(value, left_arm, right_arm, running_best): """What the running best becomes once this node has been considered.""" left = max(left_arm, 0) right = max(right_arm, 0) return max(running_best, value + left + right) print(top_out(-3, 0, 0, 0))print(top_out(-3, 0, 0, float("-inf")))Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.