House Robber III LeetCode solution in C++

1
class Solution {
2
public:
3
vector<int> dp(TreeNode *root) {
4
vector<int> ans(2, 0); // dp[0]: maximal money you can get by robbing current node.
5
// dp[1]: maximal money you can get when not rob this node
6
if (root == NULL) return ans;
7
vector<int> left = dp(root->left);
8
vector<int> right = dp(root->right);
9
ans[0] = root->val + left[1] + right[1];
10
ans[1] = max(left[0], left[1]) + max(right[0], right[1]);
11
return ans;
12
}
13
int rob(TreeNode *root) {
14
vector<int> ans = dp(root);
15
return max(ans[0], ans[1]);
16
}
17
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0