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.

http://www.lintcode.com/en/problem/house-robber/

Discussion

不能连续rob两家,跟不能连续取两个硬币一个道理,完全就是Maximum Coins Value那道题。

class Solution {
public:
    /**
     * @param A: An array of non-negative integers.
     * return: The maximum amount of money you can rob tonight
     */
    long long houseRobber(vector<int> A) {
        long long result;
        if(A.empty()) return 0;
        int n = A.size();
        long long a = 0;
        long long b = A[0];
        result = b;
        for(int i=2; i<=n; i++) {
            result = max(A[i-1] + a, b);
            a = b;
            b = result;
        }
        return result;
    }
};

results matching ""

    No results matching ""