LeetCode-House Robber II

LiBlog發表於2016-08-02

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:

First method: consider two cases (a) rob first house, (b) not rob first house. For each case, we calculate two arrays robThis[i] and notRobThis[i], i.e., the max profit we can get with/without robbing ith house, and we always have

robThis[i] = notRobThis[i-1]+nums[i];

notRobThis[i] = max(robThis[i-1], notRobThis[i-1]);

At last, we just compare (a) rob first house case's notRobThis[n], (b) not rob first house case's robThis[n]. As we are not allowed to rob both of 1st and last houses.

 

Solution:

 1 public class Solution {
 2     public int rob(int[] nums) {
 3         if (nums.length==0) return 0;
 4         if (nums.length==1) return nums[0];
 5 
 6         int rFirstAThis = nums[0];
 7         int rFirstNoThis = 0;
 8         int nrFirstRThis = 0;
 9         int nrFirstNoThis = 0;
10 
11         for (int i=1;i<nums.length;i++){
12             int pre = rFirstAThis;
13             rFirstAThis = rFirstNoThis + nums[i];
14             rFirstNoThis = Math.max(pre,rFirstNoThis);
15 
16             pre = nrFirstRThis;
17             nrFirstRThis = nrFirstNoThis + nums[i];
18             nrFirstNoThis = Math.max(pre,nrFirstNoThis);
19         }
20 
21         return Math.max(rFirstNoThis,nrFirstRThis);
22     }
23 }

Solution 2:

We can just exclude 1st house / last house and do house robber I twice, and compare the results.

Actually the same idea, but different implementation.

相關文章