[leetcode 198] 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.

题意:给你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);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值