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 C#
int MaxGain(TreeNode node) {
if (node == null) return 0;
int leftGain = Math.Max(MaxGain(node.left), [1]);
return node.val + leftGain;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using node.val instead of 0 causes incorrect sums when child is negative.
Returning negative values decreases the path sum.
✗ Incorrect
We use 0 to ignore negative gains from child nodes, so the path sum does not decrease.
2fill in blank
mediumComplete the code to update the global maximum path sum including the current node and both children.
DSA C#
int leftGain = Math.Max(MaxGain(node.left), 0); int rightGain = Math.Max(MaxGain(node.right), 0); int priceNewPath = node.val + leftGain + [1]; maxSum = Math.Max(maxSum, priceNewPath);
Attempts:
3 left
💡 Hint
Common Mistakes
Adding node.val twice instead of rightGain.
Adding leftGain again 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 for recursion to parent node.
DSA C#
return node.val + Math.Max([1], rightGain);
Attempts:
3 left
💡 Hint
Common Mistakes
Returning priceNewPath includes both children, which is invalid for recursion.
Returning maxSum is incorrect as it is a global variable.
✗ 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 updates maxSum and returns max gain.
DSA C#
int MaxGain(TreeNode node) {
if (node == null) return 0;
int leftGain = Math.Max(MaxGain(node.left), [1]);
int rightGain = Math.Max(MaxGain(node.right), [2]);
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 node.val instead of 0 causes incorrect calculations.
Using negative values decreases the path sum.
✗ Incorrect
We use 0 to ignore negative gains from both left and right children.
5fill in blank
hardFill all three blanks to complete the main function that initializes maxSum and calls MaxGain.
DSA C#
public int MaxPathSum(TreeNode root) {
maxSum = [1];
MaxGain([2]);
return [3];
}Attempts:
3 left
💡 Hint
Common Mistakes
Initializing maxSum to 0 causes wrong results if all nodes are negative.
Returning root instead of maxSum.
✗ Incorrect
maxSum starts at int.MinValue to handle negative values; call MaxGain on root; return maxSum.
