LeetCode 198-House Robber

本文详细解释了一个专业的抢劫者如何在不触发相邻房屋警报系统的情况下,从整条街道上的房子中掠夺最大金额的方法。通过动态规划算法,文章提供了一种策略来最大化抢劫所得,同时避免触发报警机制。

摘要生成于 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.

题目解析:该题就是说给你连续的一串数,取得每一个数至少有一个间隔,找出所取得数之和所能达到的最大值?

该题的关键点在于由少至多慢慢增加,当只有一个数的时候自然是temp[0]最大,两个时候和就是temp[0]、temp[1]中大的哪一个,三个的时候就是看temp[0]+tem[2]与temp[1]谁大,比较出来后,可以将0和2的和合并,等3进来后,任然只有(temp)1、2、3三个元素.

代码

public class Solution {
    public int rob(int[] nums) {
	    	int[] temp=nums;
	    	if(temp.length==0)return 0;
	    	if(temp.length==1)return temp[0];
	    	if(temp[1]<temp[0])temp[1]=temp[0];
	    	for(int i=2;i<temp.length;i++){
	    		if((temp[i]+temp[i-2])<temp[i-1])
	    		{
	    			temp[i]=temp[i-1];
	    					
	    		}else{
	    			temp[i]=temp[i]+temp[i-2];
	    		}
	    	}
			return temp[temp.length-1];
	        
	    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值