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.

分析:

这题目是个比较简单的坐标动态规划,如果用vector做,space complexity是O(n),但是可以通过方法2,3优化为O(1);

解法1:

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) {
        // write your code here
        if (A.size() == 0) {
            return 0;
        }
        int n = A.size();
        vector<long long> res(n, INT_MIN);
        res[0] = A[0];
        res[1] = max(A[0], A[1]);
        for (int i = 2; i < A.size(); i++) {
            res[i] = max(res[i - 1], res[i - 2] + A[i]);
        }
        return res[n - 1];
    }
};

解法2:

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) {
        // write your code here
        int n = A.size();
        if (n == 0) {
            return 0;
        }
        if (n == 1) {
            return A[0];
        }
        long even = A[0];
        long odd = max(A[0], A[1]);
        long res = INT_MIN;
        for (int i = 2; i < n; i++) {
            if (i % 2 == 0) {
                res = max(even + A[i], odd);
                if (res == even + A[i]) {
                    even = even + A[i];
                } else {
                    even = odd;
                }
            } else {
                res = max(odd + A[i], even);
                if (res == odd + A[i]) {
                    odd = odd + A[i];
                } else {
                    odd = even;
                }
            }
        }
        return res;
    }
};

解法3:

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) {
        // write your code here
        int n = A.size();
        if (n == 0) {
            return 0;
        }
        if (n == 1) {
            return A[0];
        }

        vector<long long> res(2, 0);
        res[0] = A[0];
        res[1] = max(A[0], A[1]);
        for (int i = 2; i < n; i++) {
            res[i % 2] = max(res[(i - 1) % 2], res[(i - 2) % 2] + A[i]);
        }
        return res[(n - 1) % 2];
    }
};

results matching ""

    No results matching ""