MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / maxPathSumHelper

Function maxPathSumHelper

kotlin/Trees/MaximumPathSum.kt:21–36  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

19}
20
21fun maxPathSumHelper(node: TreeNode?, maxSum: MutableList<Int>): Int {
22 // Base case: null nodes have no path sum.
23 if (node == null) {
24 return 0
25 }
26 // Collect the maximum gain we can attain from the left and right
27 // subtrees, setting them to 0 if they're negative.
28 val leftSum = Math.max(maxPathSumHelper(node.left, maxSum), 0)
29 val rightSum = Math.max(maxPathSumHelper(node.right, maxSum), 0)
30 // Update the overall maximum path sum if the current path sum is
31 // larger.
32 maxSum[0] = Math.max(maxSum[0], node.value + leftSum + rightSum)
33 // Return the maximum sum of a single, continuous path with the
34 // current node as an endpoint.
35 return node.value + Math.max(leftSum, rightSum)
36}

Callers 1

maxPathSumFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected