Overview
This is a foundational 1D DP problem. You are iterating through an array, and at each step, you must make a choice: take the current element or skip it.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Find the maximum amount of money you can rob from a row of houses without alerting the police (no two adjacent houses).
This is a foundational 1D DP problem. You are iterating through an array, and at each step, you must make a choice: take the current element or skip it.
The core rule is you cannot take adjacent elements. This directly forms the recurrence relation.
At house `i`, you can either: 1) Rob it, meaning you must add its value to `dp[i-2]`. 2) Skip it, meaning you keep the max from `dp[i-1]`. `dp[i] = max(nums[i] + dp[i-2], dp[i-1])`.
Because `dp[i]` only depends on `dp[i-1]` and `dp[i-2]`, you only need two variables to track the state, reducing space complexity to O(1).