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.

Solution:

class Solution {
public:
    int rob(vector<int>& nums) {
        int n = nums.size();
        if ( n == 0 ) return 0;
        if ( n == 1 ) return nums[0];
        // p1: ...00, p2: ...10, p3: ...01
        vector<int> p1(n, 0), p2(n, 0), p3(n, 0);
        p1[1] = 0;
        p2[1] = nums[0];
        p3[1] = nums[1];
        for ( int i = 2; i <= n-1; i++ ) {
            p1[i] = p2[i-1];
            p2[i] = p3[i-1];
            p3[i] = max(p1[i-1], p2[i-1]) + nums[i];
        }
        return max(p1[n-1], max(p2[n-1], p3[n-1]));
    }
};

Notes
Pay attention to the following situation:

 1 4 3 100

Note that if nums[0] = 1 is robbed, the next robbed house can either be nums[2] or nums[3]. The two robbed house can be separated by either 1 house or 2 houses. We have to keep record of three situations, so that all the cases are considered.

results matching ""

    No results matching ""