zoukankan      html  css  js  c++  java
  • 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.

    Notice This is an extension of House Robber.

    Example

    nums = [3,6,4], return 6

    这题的做法是run两遍House Robber的算法 一遍包含第一个house不包含最后一个 二遍包含最后一个房子不包含第一个房子

    实际上cover了三种case:1 含第一个不含最后一个 2 含最后一个不含第一个 3 两个全不包含

    复制代码
     1 public class Solution {
     2     /**
     3      * @param nums: An array of non-negative integers.
     4      * return: The maximum amount of money you can rob tonight
     5      */
     6     public int houseRobber2(int[] nums) {
     7         // write your code here
     8         if(nums==null||nums.length==0){
     9             return 0;
    10         }
    11         if(nums.length==1) return nums[0];
    12         
    13         return Math.max(helper(nums, 0, nums.length-2), helper(nums, 1, nums.length-1));
    14     }
    15     private int helper(int[] nums, int start, int end){
    16         int f1 = 0;
    17         int f2 = 0;
    18         
    19         for(int i=start; i<=end; i++){
    20             int temp1 = f1;
    21             f1=Math.max(f1, f2+nums[i]);
    22             f2=temp1;
    23         }
    24         return f1;
    25     }
    26 }
    复制代码
  • 相关阅读:
    设置导航条上的主题一颜色
    luogu_2158【题解】欧拉函数
    luogu_1313【题解】二项式定理
    【数论学习笔记】高斯消元
    luogu_2524【题解】康托展开
    luogu_1495【题解】中国剩余定理
    【数论学习笔记】 约数
    luogu_4430 luogu_4981【题解】 Cayley定理
    【数论学习笔记】质数
    【数论学习笔记】同余
  • 原文地址:https://www.cnblogs.com/xinqiwm2010/p/6835437.html
Copyright © 2011-2022 走看看