Algo-Sim › Advanced DP
House Robber III
Medium · Advanced DP · step through it in Java, Python and C++ on your own input
DP on a tree: every node returns (best if robbed, best if skipped), computed from its children in one postorder pass.
Problem
The houses form a binary tree whose root is the only entrance. Robbing two houses joined directly by an edge (a parent and its child) sets off the alarm. Return the most money you can take.
Constraints
- 1 ≤ number of nodes ≤ 10⁴
- 0 ≤ Node.val ≤ 10⁴
Edge cases to test
- Empty tree:
0 - One node
- A chain (like the line version)
Follow-up questions
- Why return a pair from each subtree?
- The parent needs both "child robbed" and "child skipped" to decide; computing both once avoids exponential re-visits.
- What is the cost?
- O(n) time and O(h) stack for tree height h.
Solution
Java
public int rob(TreeNode root) {
int[] res = dfs(root);
return Math.max(res[0], res[1]);
}
// {best if this node is robbed, best if it is skipped}
private int[] dfs(TreeNode node) {
if (node == null) return new int[] {0, 0};
int[] l = dfs(node.left);
int[] r = dfs(node.right);
int rob = node.val + l[1] + r[1];
int skip = Math.max(l[0], l[1]) + Math.max(r[0], r[1]);
return new int[] {rob, skip};
}Python
def rob(root):
# (best if this node is robbed, best if it is skipped)
def dfs(node):
if not node:
return 0, 0
l = dfs(node.left)
r = dfs(node.right)
rob_it = node.val + l[1] + r[1]
skip = max(l) + max(r)
return rob_it, skip
res = dfs(root)
return max(res)C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int rob(TreeNode *root) {
vector<int> res = dfs(root);
return std::max(res[0], res[1]);
}
// {best if this node is robbed, best if it is skipped}
vector<int> dfs(TreeNode *node) {
if (node == nullptr)
return vector<int>{0, 0};
vector<int> l = dfs(node->left);
vector<int> r = dfs(node->right);
int rob = node->val + l[1] + r[1];
int skip = std::max(l[0], l[1]) + std::max(r[0], r[1]);
return vector<int>{rob, skip};
}
};
More Advanced DP problems
- Burst Balloons (Hard)
- Travelling Salesman (Held-Karp bitmask DP) (Hard)
- Partition to K Equal Sum Subsets (Medium)
- Longest Increasing Path in a Matrix (Hard)
- Regular Expression Matching (Hard)
- Wildcard Matching (Hard)
- Best Time to Buy and Sell Stock IV (Hard)