[LintCode] 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.
Example
Given [3, 8, 4], return 8.
Challenge
O(n) time and O(1) memory.

LeetCode上的原题,请参见我之前的博客House Robber

解法一:

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) {
        if (A.size() <= 1) return A.empty() ? 0 : A[0];
        vector<long long> dp{A[0], max(A[0], A[1])};
        for (int i = 2; i < A.size(); ++i) {
            dp.push_back(max(dp[i - 2] + A[i], dp[i - 1]));
        }
        return dp.back();
    }
};

解法二:

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 a = 0, b = 0;
        for (int i = 0; i < A.size(); ++i) {
            if (i % 2 == 0) {
                a += A[i];
                a = max(a, b);
            } else {
                b += A[i];
                b = max(a, b);
            }
        }
        return max(a, b);
    }
};

解法三:

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 a = 0, b = 0;
        for (int i = 0; i < A.size(); ++i) {
            long long m = a, n = b;
            a = n + A[i];
            b = max(m, n);
        }
        return max(a, b);
    }
};

本文转自博客园Grandyang的博客,原文链接:打家劫舍[LintCode] House Robber ,如需转载请自行联系原博主。

相关文章
|
算法
light oj 1047 - Neighbor House 动态规划
动态规划,这个和刘汝佳算法竞赛入门经典P158的数字三角形有些相似,不过是求最小的值,而且有些限制,每次走到点和上次走的点不在同一列。
35 0
|
机器学习/深度学习 C++
【PAT甲级 - C++题解】1128 N Queens Puzzle
【PAT甲级 - C++题解】1128 N Queens Puzzle
73 1
|
C++
【PAT甲级 - C++题解】1048 Find Coins
【PAT甲级 - C++题解】1048 Find Coins
54 0
|
人工智能 BI C++
【PAT甲级 - C++题解】1068 Find More Coins
【PAT甲级 - C++题解】1068 Find More Coins
98 0
|
机器学习/深度学习 C++
【PAT甲级 - C++题解】1105 Spiral Matrix
【PAT甲级 - C++题解】1105 Spiral Matrix
70 0
HDU-3635,Dragon Balls(有点难度的并查集。。。)
HDU-3635,Dragon Balls(有点难度的并查集。。。)
UPC朋友——并查集
题目描述 有一个城镇,住着n个市民。已知一些人互相为朋友。引用一个名人的话说,朋友的朋友也是朋友。意思是说如果A和B是朋友,C和B是朋友,则A和C是朋友.你的任务是数出最大朋友组的人数。
125 0