House Robber in Java (Leetcode 198): DP Approach
In this post we will go from the problem to the recurrence, watch it run in the simulator below, and then write the Java solution twice: first with a DP array (the easiest to understand), then with just two variables (the version you would write in an interview).
Prefer Watching? Here Is the Video Explanation
1. Understanding the Problem
You are a robber planning to rob houses along a street. Every house has some money inside. There is one catch: neighbouring houses share a security system, and if you break into two adjacent houses on the same night, the police are called automatically.
- You get an integer array
nums, wherenums[i]is the money in housei. - You cannot rob two adjacent houses. If you rob house
i, housesi - 1andi + 1are off limits. - Goal: return the maximum amount of money you can rob in one night without alerting the police.
Examples
Output: 4
Explanation: Rob house 1 (money = 1) and house 3 (money = 3). Total = 1 + 3 = 4.
Output: 12
Explanation: Rob house 1 (money = 2), house 3 (money = 9) and house 5 (money = 1). Total = 2 + 9 + 1 = 12.
A Tempting Idea That Does Not Work
The first thought for many people is "always rob the richest house, then skip its neighbours." Try it on [2, 3, 2]. The richest house is the middle one with 3, so you rob it and your total is 3. But robbing the first and last houses gives 2 + 2 = 4. Picking the biggest value at each step is not enough, because a choice now changes which houses stay available later. That is why we need DP.
Before reading the formula, try the simulator below. Pick an example, click "Next house", and watch what the program decides at each house.
2. Thinking in DP: The Recurrence
Stand in front of house i and ask one question: is it worth robbing this house? There are only two answers:
- Rob it: you collect
nums[i], but housei - 1is now off limits. The best you can add it to is what you had after housei - 2, so the total isnums[i] + dp[i - 2]. - Skip it: you keep the best total you already had after house
i - 1, which isdp[i - 1].
Take whichever is larger:
Here dp[i] means "the most money you can have after considering houses 0 to i." That meaning is what makes the formula work, so it is worth saying it out loud when you practise.
- With one house, there is nothing to compare:
dp[0] = nums[0]. - With two houses, you can only take one of them:
dp[1] = max(nums[0], nums[1]).
3. Step-by-Step Dry Run: nums = [2, 7, 9, 3, 1]
| Index (i) | House Money | Option 1: Rob (nums[i] + dp[i-2]) | Option 2: Skip (dp[i-1]) | Decision dp[i] |
|---|---|---|---|---|
| 0 | $2 | $2 (Base Case) | — | 2 |
| 1 | $7 | $7 | $2 | 7 |
| 2 | $9 | 9 + 2 = $11 | $7 | 11 |
| 3 | $3 | 3 + 7 = $10 | $11 | 11 |
| 4 | $1 | 1 + 11 = $12 | $11 | 12 |
Notice what happens at index 3: robbing the house would give 10, but skipping keeps 11, so we skip it. At index 4, robbing the last house on top of dp[2] gives 12. Final answer: $12
4. Java Implementation
Approach 1: DP Array (O(n) space)
This version follows the recurrence exactly. We fill an array where dp[i] is the best total after house i, and the last entry is the answer.
class Solution {
public int rob(int[] nums) {
if (nums == null || nums.length == 0) return 0;
if (nums.length == 1) return nums[0];
int n = nums.length;
int[] dp = new int[n];
// Base cases
dp[0] = nums[0];
dp[1] = Math.max(nums[0], nums[1]);
// dp[i] = best of: skip house i, or rob house i
for (int i = 2; i < n; i++) {
dp[i] = Math.max(dp[i - 1], nums[i] + dp[i - 2]);
}
return dp[n - 1];
}
}
Approach 2: Space-Optimized DP (O(1) space)
Each step only looks at the previous two values, so the whole array can be replaced by two variables: prev2 for dp[i - 2] and prev1 for dp[i - 1].
class Solution {
public int rob(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int prev2 = 0; // dp[i - 2]
int prev1 = 0; // dp[i - 1]
for (int num : nums) {
// Skip this house (prev1) or rob it (num + prev2)
int current = Math.max(prev1, num + prev2);
// Slide the window forward
prev2 = prev1;
prev1 = current;
}
return prev1;
}
}
Run It Yourself
Here is a small program that runs both versions on the examples from this post, so you can check them on your own machine:
import java.util.Arrays;
public class Main {
static int robArray(int[] nums) {
if (nums == null || nums.length == 0) return 0;
if (nums.length == 1) return nums[0];
int n = nums.length;
int[] dp = new int[n];
dp[0] = nums[0];
dp[1] = Math.max(nums[0], nums[1]);
for (int i = 2; i < n; i++) {
dp[i] = Math.max(dp[i - 1], nums[i] + dp[i - 2]);
}
return dp[n - 1];
}
static int robOptimized(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int prev2 = 0, prev1 = 0;
for (int num : nums) {
int current = Math.max(prev1, num + prev2);
prev2 = prev1;
prev1 = current;
}
return prev1;
}
public static void main(String[] args) {
int[][] tests = { {1, 2, 3, 1}, {2, 7, 9, 3, 1}, {2, 1, 1, 2}, {2, 3, 2}, {5} };
for (int[] t : tests) {
System.out.println(Arrays.toString(t)
+ " -> array DP: " + robArray(t)
+ ", optimized: " + robOptimized(t));
}
}
}
Output (I worked these out separately, so please run the program and paste your own output here):
[2, 7, 9, 3, 1] -> array DP: 12, optimized: 12
[2, 1, 1, 2] -> array DP: 4, optimized: 4
[2, 3, 2] -> array DP: 4, optimized: 4
[5] -> array DP: 5, optimized: 5
5. Complexity Analysis
- Time Complexity (both approaches):
O(n)
We walk through thenhouses once and do a constant amount of work at each one. - Space Complexity:
Approach 1 usesO(n)because of thedparray. Approach 2 usesO(1), since it only keeps two integers.
6. Common Mistakes & Follow-ups
- Mixing up the base cases:
dp[1]ismax(nums[0], nums[1]), notnums[1]. Forgetting themaxbreaks inputs like[2, 1]. - Greedy thinking: picking the biggest house first fails on
[2, 3, 2], as we saw above. - Same pattern as Climbing Stairs: each state depends only on the previous two, which is why the O(1) version works. If that idea is new to you, read my Climbing Stairs in Java post first.
- Follow-up (LeetCode 213, House Robber II): if the houses form a circle, the first and last houses are neighbours. Run this same algorithm twice, once on houses
0ton - 2and once on1ton - 1, and take the larger result. - Follow-up (LeetCode 337, House Robber III): the houses form a binary tree, which you can solve with a post-order traversal.
Comments
Post a Comment