zoukankan      html  css  js  c++  java
  • 213. House Robber II

    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. Credits: Special thanks to @Freezen
    for adding this problem and creating all test cases.

    这道题是之前那道House Robber 打家劫舍的拓展,现在房子排成了一个圆圈,则如果抢了第一家,就不能抢最后一家,因为首尾相连了,所以第一家和最后一家只能抢其中的一家,或者都不抢,那我们这里变通一下,如果我们把第一家和最后一家分别去掉,各算一遍能抢的最大值,然后比较两个值取其中较大的一个即为所求。那我们只需参考之前的House Robber 打家劫舍中的解题方法,然后调用两边取较大值,代码如下:

    public int rob(int[] nums) {
            if (nums == null || nums.length == 0) return 0;
            if (nums.length == 1) return nums[0];
            int robNo = 0, robYes = nums[0];
            for (int i = 1; i < nums.length - 1; i++) {
                int temp = robNo;
                robNo = Math.max(robNo, robYes);
                robYes = temp + nums[i];
            }
            int ans = Math.max(robNo, robYes);
             robNo = 0;
             robYes = nums[1];
            for (int i = 2; i < nums.length; i++) {
                int temp = robNo;
                robNo = Math.max(robNo, robYes);
                robYes = temp + nums[i];
            }
            ans = Math.max(Math.max(robNo, robYes), ans);
            return ans;
            
        }
    

      

  • 相关阅读:
    操作系统:中断和异常
    操作系统
    编程:判断一个点是否在三角形内部
    python 多态
    python super()函数:调用父类的构造方法
    python 继承机制(子类化内置类型)
    python 父类方法重写
    python 继承机制
    python 封装底层实现原理
    python 类的封装
  • 原文地址:https://www.cnblogs.com/apanda009/p/7284504.html
Copyright © 2011-2022 走看看