Wednesday, December 7, 2022

[Uber][LeetCode] House Robber III

Problem: The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root.

Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night.

Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.

Example:

Input: root = [3,2,3,null,3,null,1]
Output: 7
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

Input: root = [3,4,5,1,3,null,1]
Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.


Approach: We can use post order traversal here. At every node the maximum money can be one of the following:

  1. Including node : Money at node + Max money without including direct left node + Max money without including direct right node
  2. Without including node: Max money with/ without including left node + Max money with or with out including direct right node

That's all!


Implementation in C#:

    public int Rob(TreeNode root)
    {
int[] sums = this.RobHelper(root);
return Math.Max(sums[0], sums[1]);
}

private int[] RobHelper(TreeNode node)
{
if (node != null)
{
int[] leftSum = this.RobHelper(node.left);
int[] rightSum = this.RobHelper(node.right);

int sumIncludingNode = leftSum[1] + rightSum[1] + node.val;
int sumDiscludingNode = Math.Max(leftSum[0], leftSum[1]) +
                Math.Max(rightSum[0], rightSum[1]);

return new int[] { sumIncludingNode, sumDiscludingNode };
}

return new int[2];
}

Complexity: O(n)

No comments:

Post a Comment