leetocode213_House_Roubber2

前面写过一道,在一条街道上如何抢劫的最多,这道题是那道题的继承。关键之处在于,前面的那个街道,变成了环形的。
使用java写出DP方程,dp[0] = nums[0], dp[1] = Math.max(nums[0], nums[1])
dp[i] = math.max(dp[i-2] + nums[i], dp[i - 1]),
我是直接写出了一个DPHelper,同样可以解决一条街

public static int robHelper (int[] nums, int lo, int hi) {
        int preRob = 0; //  simple explain
        int preNotRob = 0;
        int rob = 0;
        int notRob = 0;
        for (int j = lo; j <= hi; j++) {
            // what is the include and exclude
            rob = preNotRob + nums[j];
            notRob = Math.max(preRob, preNotRob);

            preRob = rob;
            preNotRob = notRob;

        }
        return Math.max(rob, notRob);

    }

环形街道的话。

public static int rob(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        if (nums.length == 1) {
            return nums[0];
        }
        if (nums.length == 2) {
            return Math.max(nums[0], nums[1]);
        }

        return Math.max(robHelper(nums, 0, nums.length - 2), robHelper(nums, 1, nums.length - 1));
       // this is an extension of House Robber

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值