LeetCode House Robber

本文探讨了一个经典的动态规划问题——打家劫舍问题。问题设定为抢劫者不能连续抢劫相邻房屋以避免触发警报。文章通过动态规划的方法提供了解决方案,并给出了两种实现方式:一种使用数组存储中间结果,另一种则采用更高效的O(1)空间复杂度的解决方案。

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

思路分析:典型的动态规划,和求最大和子数组有点类似,global[i] 表示num[0...i]之间的最优解,那么DP方程可以写作global[i] = Max(global[i-2] +  num[i], global[i-1]),分别对应于取num[i](此时不能取num[i-1])和不num[i]的最优解,然后取max即可。是一个一维DP,时间和空间复杂度都是O(n)。

AC Code

public class Solution {
    public int rob(int[] num) {
        //1218
        int n = num.length;
        if(n == 0) return 0;
        if(n == 1) return num[0];
        
        int []global = new int [n];
        global[0] = num[0];
        global[1] = Math.max(num[0], num[1]);
        for(int i = 2; i < n; i++){
            global[i] = Math.max(global[i-2] + num[i], global[i-1]);//Max(chooseNum[i], notChooseNum[i])
        }
        return global[n-1];
        //1224
    }
}
优化后只有O(1)空间的代码如下,分别用a和b对奇数index和偶数index的数取local max,每次计算要更新全局max。
 public int rob(int[] num) {
        if(num == null || num.length  == 0) return 0;
        int a = 0; //odd
        int b = 0; //even
        
        for(int i = 0; i < num.length; i++){
            if(i%2 == 0){
                b += num[i];
                b = Math.max(a, b);
            } else{
                a += num[i];
                a = Math.max(a, b);
            }
        }
        return Math.max(a,b);
    }





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值