CodeArchon

hardTreesFacebookAmazonMicrosoftGoogle

Maximum Current Path

A power grid analyst routes current through a branching junction network; some junctions amplify and others resist. Find the single path with maximum net current flow.

Given the root of a binary tree, return the maximum path sum of any non-empty path. A path may start and end at any node and does not need to pass through the root.

Choose approach

-10
9
g=9
currpivot
20
15
7
1/6
Narrationstep 1 of 6

Node 9: path-through = 9 + 0 + 0 = 9. New best!

1def maxPathSum(root):
2 best = float('-inf')
3 def gain(node):
4 nonlocal best
5 if not node: return 0
6 l = max(0, gain(node.left))
7 r = max(0, gain(node.right))
8 best = max(best, node.val + l + r)
9 return node.val + max(l, r)
10 gain(root)
11 return best
Variables
node=9
left=0
right=0
through=9
best=9

How to think about it

  1. Negative subtree contribution is replaced by 0 (skip that branch).
  2. At every node, consider the inverted-V path: left + node + right.
  3. Only propagate one side upward: parent can only extend one of your subpaths.

Edge cases to catch in interview

  • All negative values -> best is the single largest value.
  • Single node -> that value.

Examples

Example 16
{"arr":[1,2,3]}
Example 242
{"arr":[-10,9,20,null,null,15,7]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed