AlgoMaster Logo

House Robber III

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Recursive DFS (Depth-First Search)

Intuition:

The problem is an extension of the House Robber problem. Here, the houses are in the form of a binary tree, and the rule is the same: we cannot rob two directly-linked houses. A straightforward way to solve this problem is to use DFS and recursion to consider all possible combinations of robbing/not robbing a node and calculate the maximum amount.

The basic idea is:

  • For each node, we have two choices: rob this house or not.
  • If we rob this house, we cannot rob its children but can consider its grandchildren.
  • If we do not rob this house, we can move to its children freely.

Code:

2. DFS with Memoization

Intuition:

To optimize the above approach, we implement memoization. The recursive approach recalculates the same values multiple times. Instead, we can store the results for each subtree for a node, which saves computation time.

We use a HashMap to store the result for each node so we don't compute the value of a node more than once.

Code:

3. Optimized DFS with Return Values (Most Optimal)

Intuition:

Rather than relying solely on memoization, we can optimize further by using a pair of values returned for each node:

  • The maximum money that can be robbed if the current node is not robbed.
  • The maximum money that can be robbed if the current node is robbed.

This approach allows us to eliminate the use of an external hashmap by encompassing all information in a succinct recursive return.

Code: