Skip to content
AI360Xpert
Back to 1-D Dynamic Programming
Medium

House Robber

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into 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

Input:nums = [1,2,3,1]
Output:4
Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4.
Input:nums = [2,7,9,3,1]
Output:12
Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.

Constraints

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 400

Dynamic Programming (Space Optimized)

Approach

For each house `i`, we have two choices: rob it or skip it. If we rob it, we add its money to the maximum money we could rob from houses up to `i-2`. If we skip it, we take the maximum money we could rob from houses up to `i-1`. So, the DP recurrence is: `dp[i] = max(dp[i-1], dp[i-2] + nums[i])`. Since we only need the last two values (`dp[i-1]` and `dp[i-2]`), we can optimize space by using just two variables instead of a full array.

Complexity Analysis

Time Complexity
O(n)
Space Complexity
O(1)

Time complexity is O(n) as we iterate through the array once. Space complexity is O(1) since we only use two variables for tracking state.

Solution.java
class Solution {    public int rob(int[] nums) {        if (nums == null || nums.length == 0) return 0;        if (nums.length == 1) return nums[0];                int rob1 = 0; // max money up to i-2        int rob2 = 0; // max money up to i-1                for (int num : nums) {            // max(rob current house + money up to i-2, skip current house)            int temp = Math.max(num + rob1, rob2);            rob1 = rob2;            rob2 = temp;        }                return rob2;    }}