House Robber - Problem
The House Robber Challenge
You're a professional robber planning the perfect heist along a residential street. Each house contains a different amount of money, but there's a catch: adjacent houses have connected security systems that will automatically alert the police if both are robbed on the same night.
Your Goal: Maximize your earnings without triggering any alarms.
Input: An integer array
Output: The maximum amount you can rob without robbing adjacent houses
Example: For houses
You're a professional robber planning the perfect heist along a residential street. Each house contains a different amount of money, but there's a catch: adjacent houses have connected security systems that will automatically alert the police if both are robbed on the same night.
Your Goal: Maximize your earnings without triggering any alarms.
Input: An integer array
nums where nums[i] represents the money in house iOutput: The maximum amount you can rob without robbing adjacent houses
Example: For houses
[2, 7, 9, 3, 1], you can rob houses 0, 2, and 4 (values 2, 9, 1) for a total of 12, which is optimal. Input & Output
example_1.py โ Basic Case
$
Input:
[2,7,9,3,1]
โบ
Output:
12
๐ก Note:
Rob houses 0, 2, and 4 with values 2, 9, and 1. Total = 2 + 9 + 1 = 12. This is optimal since we can't rob adjacent houses.
example_2.py โ Two Houses
$
Input:
[2,1]
โบ
Output:
2
๐ก Note:
Rob house 0 with value 2. Can't rob both adjacent houses, so choose the larger value.
example_3.py โ Single House
$
Input:
[5]
โบ
Output:
5
๐ก Note:
Only one house available, so rob it for maximum value of 5.
Visualization
Tap to expand
Understanding the Visualization
1
Assess Each House
Look at each house and the maximum money you could have earned up to the previous houses
2
Make Strategic Choice
Decide: Rob this house + best from 2 houses ago, or skip and keep the best from the previous house
3
Build Optimal Path
Each decision builds upon previous optimal decisions, ensuring the best overall strategy
4
Maximum Heist Complete
The final house gives you the maximum money possible without triggering any alarms
Key Takeaway
๐ฏ Key Insight: At each house, we only need to remember the maximum money from the previous house and two houses back. This transforms an exponential problem into a linear one by avoiding redundant calculations and building the optimal solution incrementally.
Time & Space Complexity
Time Complexity
O(2^n)
Each house has 2 choices, creating a binary tree of depth n
โ Quadratic Growth
Space Complexity
O(n)
Recursion stack depth can go up to n levels
โก Linearithmic Space
Constraints
- 1 โค nums.length โค 100
- 0 โค nums[i] โค 400
- Adjacent houses cannot be robbed on the same night
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code