Skip to content

Commit b6d3024

Browse files
committed
Add Maximum Path Sum
1 parent 9466a23 commit b6d3024

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

kotlin/Trees/MaximumPathSum.kt

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import ds.TreeNode
2+
3+
/*
4+
Definition of TreeNode:
5+
6+
data class TreeNode(
7+
var value: Int,
8+
var left: TreeNode? = null,
9+
var right: TreeNode? = null
10+
)
11+
*/
12+
13+
fun maxPathSum(root: TreeNode?): Int {
14+
// In Kotlin, global variable is bad practice.
15+
// So, we use a mutable list to store the max sum and access it by reference.
16+
var maxSum = mutableListOf(Int.MIN_VALUE)
17+
maxPathSumHelper(root, maxSum)
18+
return maxSum[0]
19+
}
20+
21+
fun 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+
}

0 commit comments

Comments
 (0)