Skip to content

Commit

Permalink
House Robber III - another implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
haoel committed Mar 24, 2019
1 parent 4905e7f commit 5353720
Showing 1 changed file with 47 additions and 1 deletion.
48 changes: 47 additions & 1 deletion algorithms/cpp/houseRobber/houseRobberIII.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Source : https://leetcode.com/problems/house-robber-iii/
// Author : Calinescu Valentin
// Author : Calinescu Valentin, Hao Chen
// Date : 2016-04-29

/***************************************************************************************
Expand Down Expand Up @@ -86,3 +86,49 @@ class Solution {
return dict[root];
}
};


// Another implementation - Hao Chen

class Solution {
public:
int max(int a, int b) {
return a > b ? a: b;
}
int max(int a, int b, int c) {
return max(a, max(b,c));
}
int max(int a, int b, int c, int d) {
return max(a, max(b, max(c,d)));
}

void rob_or_not(TreeNode* root, int& max_robbed, int& max_not_robbed) {
// NULL room return 0;
if (root == NULL) {
max_robbed = max_not_robbed = 0;
return ;
}

// we have two options, rob current room or not.
int max_left_robbed, max_left_not_robbed;
int max_right_robbed, max_right_not_robbed;
rob_or_not(root->left, max_left_robbed, max_left_not_robbed);
rob_or_not(root->right, max_right_robbed, max_right_not_robbed);

// If root is robbed, then both left and right must not be robbed.
max_robbed = root->val + max_left_not_robbed + max_right_not_robbed;

// If root is not robbed, then 4 combinations are possible:
// left is robbed or not and right is either robbed or not robbed,
max_not_robbed = max(max_left_robbed + max_right_robbed,
max_left_robbed + max_right_not_robbed,
max_left_not_robbed + max_right_robbed,
max_left_not_robbed + max_right_not_robbed);

}
int rob(TreeNode* root) {
int robbed, not_robbed;
rob_or_not(root, robbed, not_robbed);
return max(robbed, not_robbed);
}
};

0 comments on commit 5353720

Please sign in to comment.