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: 

    if the last one is not robbed, then you are free to choose whether to rob the first one. you can break the circle by assuming the first house is not robbed.

    For example, 1 -> 2 -> 3 -> 1 becomes 2 -> 3 if 1 is not robbed.

    Since every house is either robbed or not robbed and at least half of the houses are not robbed, the solution is simply the larger of two cases with consecutive houses, i.e. house i not robbed, break the circle, solve it, or house i + 1 not robbed. Hence, the following solution. I chose i = n and i + 1 = 0 for simpler coding. But, you can choose whichever two consecutive ones.

     1 class Solution {
     2     public int rob(int[] nums) {
     3         if (nums == null || nums.length == 0) return 0;
     4         if (nums.length == 1) return nums[0];
     5         return Math.max(helper(nums, 0, nums.length - 2), helper(nums, 1, nums.length - 1));
     6     }
     7     
     8     public int helper(int[] nums, int lo, int hi) {
     9         int prev2 = 0;
    10         int prev1 = nums[lo];
    11         for (int i = lo + 1; i <= hi; i++) {
    12             int temp = prev1;
    13             prev1 = Math.max(prev1, prev2 + nums[i]);
    14             prev2 = temp;
    15         }
    16         return prev1;
    17     }
    18 }
  • 相关阅读:
    kubernetes入门(03)kubernetes的基本概念
    洛谷P3245 [HNOI2016]大数(莫队)
    洛谷P4462 [CQOI2018]异或序列(莫队)
    cf997C. Sky Full of Stars(组合数 容斥)
    cf1121F. Compress String(后缀自动机)
    洛谷P4704 太极剑(乱搞)
    洛谷P4926 [1007]倍杀测量者(差分约束)
    洛谷P4590 [TJOI2018]游园会(状压dp LCS)
    洛谷P4588 [TJOI2018]数学计算(线段树)
    洛谷P4592 [TJOI2018]异或(可持久化01Trie)
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5053679.html
Copyright © 2011-2022 走看看