# 198. House Robber

You 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.

Example 1:

``````Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
``````

Example 2:

``````Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
``````

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

``````class Solution {
public:
int rob(vector<int>& nums) {
if (nums.size() <= 1) return nums.empty() ? 0 : nums[0];
vector<int> dp = {nums[0], max(nums[0], nums[1])};
for (int i = 2; i < nums.size(); ++i) {
dp.push_back(max(nums[i] + dp[i - 2], dp[i - 1]));
}
return dp.back();
}
};
``````

``````class Solution {
public:
int rob(vector<int>& nums) {
int robEven = 0, robOdd = 0, n = nums.size();
for (int i = 0; i < n; ++i) {
if (i % 2 == 0) {
robEven = max(robEven + nums[i], robOdd);
} else {
robOdd = max(robEven, robOdd + nums[i]);
}
}
return max(robEven, robOdd);
}
};
``````

``````class Solution {
public:
int rob(vector<int>& nums) {
int rob = 0, notRob = 0, n = nums.size();
for (int i = 0; i < n; ++i) {
int preRob = rob, preNotRob = notRob;
rob = preNotRob + nums[i];
notRob = max(preRob, preNotRob);
}
return max(rob, notRob);
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/198

House Robber II

House Robber III

Maximum Product Subarray

Paint House

Paint Fence

Coin Path

Non-negative Integers without Consecutive Ones

Delete and Earn

https://leetcode.com/problems/house-robber/description/

https://leetcode.com/problems/house-robber/discuss/55681/java-on-solution-space-o1

https://leetcode.com/problems/house-robber/discuss/55693/c-1ms-o1space-very-simple-solution

https://leetcode.com/problems/house-robber/discuss/55695/java-dp-solution-on-runtime-and-o1-space-with-inline-comment

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation