House Robber
MediumNeetCode 150Top Interview 150 1-D Dynamic ProgrammingCARS24FreechargeCiscoDatabricksGrabProblem
Houses stand in a row and nums[i] is the cash inside house i.
If you rob two houses that are next to each other, the alarm sounds, so you may never rob neighbours.
Return the largest total cash you can take without setting off the alarm.
Constraints
- 1 ≤ nums.length ≤ 100
- 0 ≤ nums[i] ≤ 400
Examples: pick one to animate
Solutions
TimeO(n)
SpaceO(n)
Time: One pass over the houses, with one comparison for each.
Space: The dp array holds n + 1 values.
dp[i] is the best loot from the first i houses. For house
i-1, either skip it and keep dp[i-1], or rob it and add its cash to
dp[i-2], which keeps its neighbour untouched.