zoukankan      html  css  js  c++  java
  • [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);
        }
    };
  • 相关阅读:
    redis集群报错:(error) MOVED 5798 127.0.0.1:7001
    20190829小记
    20181114小结记录
    遇到的面试题记录
    机器学习-KNN算法原理 && Spark实现
    机器学习-KMeans算法原理 && Spark实现
    大数据开发-生产中遇到的10个致命问题
    大数据开发-Spark-闭包的理解
    大数据开发-Spark-共享变量之累加器和广播变量
    大数据开发-Spark-RDD的持久化和缓存
  • 原文地址:https://www.cnblogs.com/grandyang/p/5445889.html
Copyright © 2011-2022 走看看