[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.


public class Solution {
    public int rob(int[] nums) {
        if(nums.length<1) return 0;
        int maxSoFar=nums[0];
        int lastIndex=0;
        int lastMax=0;
        //33,1,2,3
        for(int i=1; i<nums.length; i++){
            if(i-lastIndex==1)
            {
                int temp=lastMax+nums[i];
                if(temp>maxSoFar){
                    lastMax=maxSoFar;
                    maxSoFar=temp;
                    lastIndex=i;
                }else
                    lastMax=temp;
            }
            else{
                lastMax=maxSoFar;
                lastIndex=i;
                maxSoFar+=nums[i];
            }
         
        }
        
        return maxSoFar;
    }
}

Dynamic Programming


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值