首页 > 代码库 > House Robber II

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 }

House Robber II