Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solution for HOUSE ROBBER PROBLEM III #789

Merged
merged 1 commit into from
Oct 29, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions Leetcode Solutions/HOUSE ROBBER III.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/* Author : JaiSehgal007 */

/* House Robber Problem III from Leetcode */

/* Link to the Problem : https://leetcode.com/problems/house-robber-iii/ */

/*
PROBLEM DESCRIPTION:
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.
*/

/*
EXAMPLES TO THE PROBLEM:
Example 1:
Input: root = [3,2,3,null,3,null,1]
Output: 7
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
Input: root = [3,4,5,1,3,null,1]
Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.
*/

/*-------------------------------------SOLUTION---------------------------------------*/
class Solution {
public:
int robber(TreeNode* root,int &l,int &r){
if(!root)return 0;
int ll=0,lr=0,rl=0,rr=0;
l=robber(root->left,ll,lr);
r=robber(root->right,rl,rr);

return max(l+r,root->val+ll+lr+rl+rr);

}
int rob(TreeNode* root) {
int l,r;
return robber(root,l,r);
}
};