Saturday, December 17, 2016

House Robber -- LeetCode 198

[Question]
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.
[Analysis]
Assume the S(n) is the largest amount the robber can get from H[0,1,...n],
        S(n) = max(  S(n-1), S(n-2) + H[n] )
       
Further, we can assume there are two additional house before H[0], with zero assets. Use dynamic programming from the beginning of the Houses, we can S(0),... S(n). S(n) is the answer.

[Solution]
class Solution {
public:
    int rob(vector<int>& nums) {
        if (nums.empty()) return 0;

        int a=0, b=0, c=0;
        for (int i=0; i<nums.size(); i++) {
            c = max(b, a+nums[i]);
            a=b, b=c;
        }          
        return c;
    }

};

No comments:

Post a Comment