House RobberYou are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and

it will automatically contact the police if two adjacent houses were broken into on the same night.Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight

without alerting the police.

Credits:

Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

Dynamic programming.

dp[i] stores the value I get if I robbed the ith house and previous available houses.

The answer should be the maximum of last two elements in dp.

Walk through is important. I fix two bugs when I test my code with the input “2 3” and “0 2 3”.

At first glance, I misread the title as “Horse Rubber”. I thought why I have to rub horse at night? And why the police may arrest me if I rub two adjacent horses?

Anyway, it doesn’t harm the correctness of the code.

class Solution { public: int rob(vector<int>& nums) { if(nums.size() == 0) return 0; if(nums.size() == 1) return nums[0]; if(nums.size() == 2) return max(nums[0], nums[1]); //size is bigger than 2 int dp[nums.size()]; memset(dp, 0, sizeof(dp)); dp[0] = nums[0]; dp[1] = nums[1]; for(size_t i = 2; i < nums.size(); i++){ for(size_t j = 0; j < i - 1; j++){ int value = dp[j] + nums[i]; if(value > dp[i]) dp[i] = value; } } return max(dp[nums.size() - 1], dp[nums.size() - 2]); } };