zoukankan      html  css  js  c++  java
  • LeetCode-House Robber II

    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.

    Analysis:

    First method: consider two cases (a) rob first house, (b) not rob first house. For each case, we calculate two arrays robThis[i] and notRobThis[i], i.e., the max profit we can get with/without robbing ith house, and we always have

    robThis[i] = notRobThis[i-1]+nums[i];

    notRobThis[i] = max(robThis[i-1], notRobThis[i-1]);

    At last, we just compare (a) rob first house case's notRobThis[n], (b) not rob first house case's robThis[n]. As we are not allowed to rob both of 1st and last houses.

    Solution:

     1 public class Solution {
     2     public int rob(int[] nums) {
     3         if (nums.length==0) return 0;
     4         if (nums.length==1) return nums[0];
     5 
     6         int rFirstAThis = nums[0];
     7         int rFirstNoThis = 0;
     8         int nrFirstRThis = 0;
     9         int nrFirstNoThis = 0;
    10 
    11         for (int i=1;i<nums.length;i++){
    12             int pre = rFirstAThis;
    13             rFirstAThis = rFirstNoThis + nums[i];
    14             rFirstNoThis = Math.max(pre,rFirstNoThis);
    15 
    16             pre = nrFirstRThis;
    17             nrFirstRThis = nrFirstNoThis + nums[i];
    18             nrFirstNoThis = Math.max(pre,nrFirstNoThis);
    19         }
    20 
    21         return Math.max(rFirstNoThis,nrFirstRThis);
    22     }
    23 }

    Solution 2:

    We can just exclude 1st house / last house and do house robber I twice, and compare the results.

    Actually the same idea, but different implementation.

  • 相关阅读:
    进击的UI------------UIToolBar(bottom导航条)
    进击的UI-------------------UIPageControl(滑动控制)
    进击的UI---------------------UIStepper(加减)
    进击的UI--------------UIActionSheet(提示)
    python生成固定格式且不会重复的用户名
    python多判断if,elif语句优化
    python代码出现异常,自动重新运行
    批处理+adb命令实现Android截图小工具
    python爬取百度图片后自动上传
    map和filter函数
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5728820.html
Copyright © 2011-2022 走看看