House Robber
mediumBlind 75NeetCode 150dynamic-programming
Problem
Given the amounts of money in a row of houses, find the maximum you can rob without taking from two adjacent houses, since adjacent robberies trigger the alarm.
Examples
Input: nums = [1, 2, 3, 1]
Output: 4
Rob houses 1 and 3 for 1 + 3 = 4.
Input: nums = [2, 7, 9, 3, 1]
Output: 12
Rob houses with 2, 9, and 1.
Constraints
- • 1 <= nums.length <= 100
- • 0 <= nums[i] <= 400
Hints(tap to reveal)
- 1. At each house choose to skip or rob plus two back.
- 2. Carry forward two running best totals.
Optimal approach(spoiler)
- Track the best total including the current house and excluding it.
- Robbing the current house adds its value to the prior excluded best.
- Skipping keeps the prior overall best.
- Slide these two values across the row.
- O(n) time, O(1) space.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor