198. House Robber

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

 

思路:因为不能抢劫挨着的店家, 所以这道题的本质相当于在一列数组中取出一个或多个不相邻数,使其和最大,使用dp。 举例子{1,2,3,4}, f[i]表示到第i家能偷窃的最大钱数,f[0] = nums[0], f[1] = max(nums[0], nums[1]), f[2]有两种可能,就是只取f[1]或者取f[0] + f[2]. 所以递推公式是:
f[i] = Math.max(f[i - 2] + nums[i], f[i - 1]);

时间复杂度: O(n)
空间复杂度: O(n)

public class Solution {
    public int rob(int[] nums) {
        if (nums.length == 0 || nums == null) {
            return 0;
        }
        int[] f = new int[nums.length];
        f[0] = nums[0];
        if (nums.length == 1) {
            return f[0];
        }
        f[1] = nums[0] > nums[1] ? nums[0] : nums[1];
       
        if (nums.length == 2) {
            return f[1];
        }
        for (int i = 2; i < nums.length; i++) {
            f[i] = Math.max(f[i - 2] + nums[i], f[i - 1]);
        }
        return f[nums.length - 1];
    }
}

空间改进
由递推数组可以看出,并不需要n个空间,所以我们用滚动数组

时间复杂度:O(n)
空间复杂度:O(1)

public class Solution {
    public int rob(int[] nums) {
        if (nums.length == 0 || nums == null) {
            return 0;
        }
        int[] f = new int[3];
        f[0] = nums[0];
        if (nums.length == 1) {
            return f[0];
        }
        f[1] = nums[0] > nums[1] ? nums[0] : nums[1];
       
        if (nums.length == 2) {
            return f[1];
        }
        for (int i = 2; i < nums.length; i++) {
            f[i % 3] = Math.max(f[(i - 2) % 3] + nums[i], f[(i - 1) % 3]);
        }
        return f[(nums.length - 1) % 3];
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值