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 }
  • 相关阅读:
    缺失的第一个正数
    tuple用法
    整数转罗马数字
    三种时间格式的转换
    不同包的调用
    正则表达式
    lgb模板
    线性回归
    时间序列的特征
    3D聚类
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5053679.html
Copyright © 2011-2022 走看看