198. House Robber LeetCode

本文介绍了一种解决抢劫者问题的方法,该问题要求在不触发报警的前提下从一系列房屋中窃取最大金额。通过使用两个变量交替计算盗与不盗的情况,确保了在连续五家中选择两家或四家中选择一家时总能获得最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

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.

题目分析:这是一道简单题,主要是判断相邻地两家是否值得盗窃,以及如何选择。问题的症结就在可能选择盗取的那家旁边两家的价值要高于它,,这就存在选择的问题,我们可以设置两个变量用于存储盗与不盗这两种情况下的利益得失。我在本题之中设置了两个变量,a,b。a用于存储盗取nums[i]家的财物以及之前盗取的所有的财物价值之和,b就是不盗的情况。a,b的值保持同步。连续5家必选两家,4家必选一家。选择的优劣最多在达到5家的时候就可以分辨出来,这时候a,b同步为较大的那个。

代码:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值