---
# System prepended metadata

title: House Robber 198
tags: [dp, leetcode, medium]

---


# House Robber 198

###### tags: `leetcode`,`dp`,`medium`


>ref: https://leetcode.com/problems/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.

>Example 1:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.

>Example 2:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
 

>Constraints:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.



>1. record the login choice
>the max income for rub nums[i] is non-rub[i-1]+nums[i], while max income for non-rub nums[i] is max(non-rub[i-1],rub[i-1])
>2. time(O(n)), spatial(O(2N)), only use i-1 income, the array can be shorter


```java=
    public int rob(int[] nums) {
        
        int[] non_rob=new int[nums.length];
        
        int[] rob=new int[nums.length];
        
        rob[0]=nums[0];
        
        for(int i=1;i<nums.length;i++){
            non_rob[i]=Math.max(non_rob[i-1],rob[i-1]);
            rob[i]=non_rob[i-1]+nums[i];
        }
        
        return Math.max(rob[nums.length-1],non_rob[nums.length-1]);
        
    }
```

>1. time(O(n)), spatial(O\(C\)), only use i-1 income, the array can be replace by tmp 

```java=
    public int rob(int[] nums) {
        
        int[] non_rob=new int[2];
        
        int[] rob=new int[2];
        
        rob[0]=nums[0];
        
        for(int i=1;i<nums.length;i++){
            non_rob[1]=Math.max(non_rob[0],rob[0]);
            rob[1]=non_rob[0]+nums[i];
            non_rob[0]=non_rob[1];
            rob[0]= rob[1];
        }
        
        return Math.max(rob[0],non_rob[0]);
        
    }
```

```java=
    public int rob(int[] nums) {
        
        int non_rob=0,rob=0,tmp;
        rob=nums[0];
        
        for(int i=1;i<nums.length;i++){
            tmp=Math.max(non_rob,rob);
            rob=non_rob+nums[i];
            non_rob=tmp;
        }
        
        return Math.max(rob,non_rob);
        
    }
```
    
    
    
