198. 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 system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

Subscribe to see which companies asked this question

class Solution {
public:
    int rob(vector<int>& nums) {
        int n = nums.size();
        if(n==0)return 0;//开始没写这个,然后就RE了- - 
        //设置两个数组,分别为选第N个,不选第N个房子
        int *a = new int[n]; 
        int *b  = new int[n]; 
        a[0] = nums[0];
        b[0] = 0;
        for(int i=1; i<n; i++) {
            a[i] = b[i-1] + nums[i];
            b[i] = max(a[i-1], b[i-1]);//若不选第N个,则最大为是否选第N-1个的最大值
        }
        return max(a[n-1], b[n-1]);
    }
};


你可能感兴趣的:(198. House Robber)