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.
题意:给你n天的收益,你可以选择其中m天抢,但是不能在连续两天作案,求最大收益。
分析:
解法:动态规划
第一天的最大收益肯定是抢,但第二天呢?
第二天只有两种情况,第一天抢或者是第二天抢,取最大值。
那么,规则到底是什么?
实际上,对于当天来说,只有抢和不抢两种选择。
不抢是不需要前提的,但抢的话,前提条件是前一天没有抢。
所以说,对于当天的选择,只与前一天抢与不抢的状态有关系。
对于当天抢这个状态来说,最大收益显然是上一天不抢的最大收益+当天抢的收益。
对于当天不抢,他没有前提,所以对上一天抢与不抢没有要求,故当天不抢的最大收益=上一天抢和不抢之间的最大值。
上面说的有点拗口,看代码比较清晰,就是一个维护两个值的过程。
static string x = [](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return "";
}();
class Solution {
public:
int rob(vector<int>& nums) {
int q = 0, bq = 0;
for(int i = 0; i < nums.size(); ++i){
int t = max(q, bq);
q = bq + nums[i];
bq = t;
}
return max(q, bq);
}
};
本文探讨了一个经典的动态规划问题——打家劫舍。问题设定为:每栋房子都有一定数量的钱财,但相邻的房子装有相连的报警系统,若两栋相邻的房子在同一晚被抢劫,则会自动报警。给定每个房子中的金钱数额,目标是在不触动报警系统的情况下获得最大的收益。

523

被折叠的 条评论
为什么被折叠?



