LeetCode 213. House Robber II(java)

Note: This is an extension of House Robber.

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

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.

思路:作为House Robber的拓展,从直线变成圆形,那么区别就在于,第一个和最后一个只能有一个house被rob,因此,我们只需要分两种情况考虑就行,1. rob第一间房子,其余步骤和house robber一样,但是最后的结果只能留下最后一间房子不rob的答案。2. 不rob第一间房子,最后一间房子留下两个答案。最后在这三个答案里选出一个最大的返回即可。时间复杂度为O(n),空间负责度为O(1)。
class Solution {
    public int rob(int[] nums) {
        if (nums.length == 0) return 0;
        if (nums.length == 1) return nums[0];
        if (nums.length == 2) return Math.max(nums[0], nums[1]);
        //第一种情况:rob第一间房
        int rrob = nums[0], rnrob = nums[0];
        for (int i = 2; i < nums.length; i++) {
            int temp = rrob;
            rrob = rnrob + nums[i];
            rnrob = Math.max(temp, rnrob);
        }
        //第二种情况,nrob第一间房
        int nrob = nums[1], nnrob = 0;
        for (int i = 2; i < nums.length; i++) {
            int temp = nrob;
            nrob = nnrob + nums[i];
            nnrob = Math.max(temp, nnrob);
        }
        return Math.max(rnrob, Math.max(nrob, nnrob));
    }
}
此版本和上面的思路类似,代码reuse率会更好,分成不rob第一间房子和不rob最后一间房子两种情况来考虑,可以直接套用house robber的代码作为辅助函数。
class Solution {
    public int rob(int[] nums) {
        if (nums.length == 1) return nums[0];
        return Math.max(rob(nums, 1, nums.length - 1), rob(nums, 0, nums.length - 2));
    }

    private int rob(int[] nums, int lo, int hi) {
        int include = 0, exclude = 0;
        for (int j = lo; j <= hi; j++) {
            int i = include, e = exclude;
            include = e + nums[j];
            exclude = Math.max(e, i);
        }
        return Math.max(include, exclude);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值