House Robber抢劫房屋利益最大化算法详解

问题详见: 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.

解题思路:

      由题可知,可以将遍历到的数组的元素进行判断是否是第奇数个元素,DP奇数为a,DP偶数为b,然后取得其中的最大值进行动态更新a,b的值,最后结果即为啊a,b中的较大值。整个算法复杂度为 O(n) 。具体算法如下:

class Solution {
#define max(a, b) ((a)>(b)?(a):(b))
public:
    int rob(vector<int>& nums){
        int a = 0,b = 0;
        for (int i=0; iif (i%2==0) a = max(a+nums[i], b);
            else    b = max(a, b+nums[i]);
        }
        return max(a, b);    
    }
};

其提交运行结果如下:
House Robber抢劫房屋利益最大化算法详解_第1张图片

你可能感兴趣的:(C++,算法,C++,算法)