Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the maximum path sum starting from the current node.
DSA Java
int maxPathDown(TreeNode node) {
if (node == null) return 0;
int left = Math.max(0, maxPathDown(node.left));
int right = Math.max(0, maxPathDown(node.right));
maxSum = Math.max(maxSum, node.val + left + [1]);
return node.val + Math.max(left, right);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using only left child sum and ignoring right child.
Adding node.val twice.
✗ Incorrect
We add both left and right maximum path sums to node.val to consider paths passing through the node.
2fill in blank
mediumComplete the code to update the global maximum path sum.
DSA Java
maxSum = Math.max(maxSum, [1]);
Attempts:
3 left
💡 Hint
Common Mistakes
Updating maxSum with only one child's sum.
Not including node.val in the sum.
✗ Incorrect
The maximum path sum at a node can include the node value plus both left and right maximum sums.
3fill in blank
hardFix the error in the return statement to correctly propagate the maximum path sum upwards.
DSA Java
return node.val + [1](left, right);
Attempts:
3 left
💡 Hint
Common Mistakes
Using Math.min which selects the smaller sum.
Using Math.abs which is unrelated here.
✗ Incorrect
We return node.val plus the maximum of left and right sums to continue the path upwards.
4fill in blank
hardFill both blanks to compute the maximum path sum ignoring negative sums.
DSA Java
int left = Math.[1](0, maxPathDown(node.left)); int right = Math.[2](0, maxPathDown(node.right));
Attempts:
3 left
💡 Hint
Common Mistakes
Using Math.min which would select negative sums.
Using Math.abs which changes negative sums to positive incorrectly.
✗ Incorrect
We use Math.max with 0 to ignore negative sums from children.
5fill in blank
hardFill in the blanks to implement the maximum path sum function correctly.
DSA Java
public int maxPathSum(TreeNode root) {
maxSum = Integer.MIN_VALUE;
maxPathDown([1]);
return [2];
}
private int maxPathDown(TreeNode node) {
if (node == null) return 0;
int left = Math.max(0, maxPathDown(node.left));
int right = Math.max(0, maxPathDown(node.right));
maxSum = Math.max(maxSum, node.val + left + right);
return node.val + Math.max(left, right);
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning maxPathDown(root) instead of maxSum.
Calling maxPathDown with null or wrong node.
✗ Incorrect
Call maxPathDown with root, then return maxSum which holds the maximum path sum.
