Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the maximum path sum starting from the current node or 0 if negative.
DSA Java
int maxGain(TreeNode node) {
if (node == null) return 0;
int leftGain = Math.max(maxGain(node.left), [1]);
int rightGain = Math.max(maxGain(node.right), 0);
return node.val + Math.max(leftGain, rightGain);
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning negative values instead of 0 for negative child sums.
Using node.val instead of 0 as the minimum gain.
✗ Incorrect
We use 0 to ignore negative gains from child paths, so maxGain returns at least 0 for negative sums.
2fill in blank
mediumComplete the code to update the global maximum path sum including the current node and both children.
DSA Java
int priceNewpath = node.val + leftGain + [1]; maxSum = Math.max(maxSum, priceNewpath);
Attempts:
3 left
💡 Hint
Common Mistakes
Adding node.val twice.
Using 0 instead of rightGain.
✗ Incorrect
We add rightGain to include the maximum gain from the right child in the new path sum.
3fill in blank
hardFix the error in returning the maximum gain to parent node.
DSA Java
return node.val + Math.max(leftGain, [1]);
Attempts:
3 left
💡 Hint
Common Mistakes
Returning maxSum which is a global max, not a gain.
Returning node.val twice.
✗ Incorrect
We return the node value plus the maximum gain from either left or right child to continue the path upwards.
4fill in blank
hardFill both blanks to complete the recursive function that calculates maximum path sum.
DSA Java
public int maxPathSum(TreeNode root) {
maxSum = Integer.MIN_VALUE;
maxGain(root);
return [1];
}
private int maxGain(TreeNode node) {
if (node == null) return 0;
int leftGain = Math.max(maxGain(node.left), 0);
int rightGain = Math.max(maxGain(node.right), 0);
int priceNewpath = node.val + leftGain + rightGain;
maxSum = Math.max(maxSum, priceNewpath);
return node.val + Math.max(leftGain, rightGain);
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning maxGain(root) instead of maxSum.
Returning node.val or priceNewpath directly.
✗ Incorrect
The function returns the global maxSum after computing maxGain from root.
5fill in blank
hardFill all three blanks to complete the class with global maxSum and maxGain method.
DSA Java
class Solution { private int [1] = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { maxGain(root); return maxSum; } private int maxGain(TreeNode node) { if (node == null) return 0; int leftGain = Math.max(maxGain(node.left), 0); int rightGain = Math.max(maxGain(node.right), 0); int priceNewpath = node.val + leftGain + rightGain; maxSum = Math.max(maxSum, priceNewpath); return node.val + Math.max(leftGain, rightGain); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using local variables instead of class fields.
Confusing method names.
✗ Incorrect
maxSum is the global variable, maxGain is the helper method, maxPathSum is the public method.
