1. 程式人生 > >House Robber II

House Robber II

one tco span ron list tin with first http

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