Algorithm Day84 - House Robber
🧩 Problem Description
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed.
The only constraint is: adjacent houses cannot be robbed on the same night.
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
💬 Examples
Example 1
1 | Input: nums = [1,2,3,1] |
Example 2
1 | Input: nums = [2,7,9,3,1] |
💡 Intuition
This is a dynamic programming problem.
At each house i, you decide to either:
- Rob it → value =
nums[i] + dp[i-2] - Skip it → value =
dp[i-1]
Transition formula:
1 | dp[i] = max(dp[i-1], dp[i-2] + nums[i]) |
🔢 Java Code (DP Optimized)
1 | class Solution { |
⏱ Complexity Analysis
- Time: O(n) — one pass through houses.
- Space: O(1) — only two variables stored.
✍️ Summary
- A classic DP problem.
- Transition:
dp[i] = max(dp[i-1], dp[i-2] + nums[i]). - Space can be optimized to O(1).
Related problems
lc-213— House Robber IIlc-337— House Robber III