Algo-Sim › Dynamic Programming
House Robber
Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input
For each house, either skip it (keep the best so far) or rob it on top of the best from two houses back.
Problem
Houses along a street hold nums[i] money each. Robbing two adjacent houses sets off an alarm. Return the most money you can take without robbing two neighbours.
Constraints
- 1 ≤ nums.length ≤ 100
- 0 ≤ nums[i] ≤ 400
Edge cases to test
- One house
- Two houses: the larger one
- All zeros
Follow-up questions
- What if the houses form a circle?
- Run the line version twice, without the first and without the last house (LC 213).
- What if the houses form a binary tree?
- Return (rob this node, skip this node) from each subtree in a post-order DFS (LC 337): O(n).
Solution
Java
public int rob(int[] nums) {
int[] dp = new int[nums.length + 1];
dp[1] = nums[0];
for (int i = 2; i <= nums.length; i++) {
dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i - 1]);
}
return dp[nums.length];
}Python
def rob(nums):
dp = [0] * (len(nums) + 1)
dp[1] = nums[0]
for i in range(2, len(nums) + 1):
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i - 1])
return dp[len(nums)]C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int rob(vector<int> &nums) {
vector<int> dp = vector<int>(int(nums.size()) + 1);
dp[1] = nums[0];
for (int i = 2; i <= int(nums.size()); i++) {
dp[i] = std::max(dp[i - 1], dp[i - 2] + nums[i - 1]);
}
return dp[int(nums.size())];
}
};
More Dynamic Programming problems
- Climbing Stairs: Recursion → Memo → Table (Easy)
- Min Cost Climbing Stairs (Easy)
- House Robber II (Medium)
- Coin Change (Medium)
- Coin Change II (Medium)
- Perfect Squares (Medium)
- Combination Sum IV (Medium)
- Decode Ways (Medium)
- Maximum Product Subarray (Medium)
- Best Time to Buy and Sell Stock with Cooldown (Medium)
- Best Time to Buy and Sell Stock with Transaction Fee (Medium)
- Best Time to Buy and Sell Stock III (Hard)
- Longest Increasing Subsequence (Medium)
- Word Break (Medium)
- Unique Paths (Medium)
- Unique Paths II (Medium)
- Minimum Path Sum (Medium)
- Maximal Square (Medium)
- Partition Equal Subset Sum (Medium)
- Target Sum (Medium)
- Longest Common Subsequence (Medium)
- Interleaving String (Medium)
- 0/1 Knapsack (Medium)
- Edit Distance (Medium)
- Distinct Subsequences (Hard)
- Longest Palindromic Substring (Medium)
- Palindromic Substrings (Medium)
- Longest Palindromic Subsequence (Medium)
- Predict the Winner (Medium)
- Stone Game (Medium)