House Robber
Solve this ProblemTest Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ nums.length ≤ 100 - ◆
0 ≤ nums[i] ≤ 400
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Brute Force — Recursive Without Memoization
BruteAt every house, a thief has exactly two options: skip it and move on to the next house, or rob it and skip straight past the one right next door (since robbing two adjacent houses trips the alarm). Whichever of those two choices yields more money is the best outcome from that house onward, and this decision is identical in shape at every house — so it can be expressed as a recursion on "the best haul starting from house i." Trying every house as either skipped or robbed and recursing into the corresponding next house explores every valid combination, though the same sub-problems end up solved repeatedly along different branches.
O(2^n)O(n)1class Solution {
2 private int[] nums;
3
4 public int houseRobber(int[] nums) {
5 this.nums = nums;
6 return solve(0);
7 }
8
9 private int solve(int i) {
10 if (i >= nums.length) return 0;
11 int skip = solve(i + 1);
12 int take = nums[i] + solve(i + 2);
13 return Math.max(skip, take);
14 }
15}Optimal — Bottom-Up 1D DP
OptimalOnly the best haul from the two most recently finished houses is ever needed to decide the current one, so there is no reason to keep a full array of results. Two running variables — the best haul ending two houses back and the best haul ending one house back — are enough: at each house, either skip it (keep the one-house-back value) or rob it (take the two-house-back value plus this house's amount), and the larger of those becomes the new one-house-back value as the window slides forward. After sliding through every house, the most recent value holds the answer.
O(n)O(1)1class Solution {
2 public int houseRobber(int[] nums) {
3 int prev2 = 0, prev1 = 0;
4 for (int i = 0; i < nums.length; i++) {
5 int cur = Math.max(prev1, prev2 + nums[i]);
6 prev2 = prev1;
7 prev1 = cur;
8 }
9 return prev1;
10 }
11}